Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / 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 com.att.bpm.scripts;
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.runtime.Execution
25 import org.apache.commons.lang3.*
26
27 import javax.xml.parsers.DocumentBuilder
28 import javax.xml.parsers.DocumentBuilderFactory
29
30 import org.apache.commons.codec.binary.Base64
31 import org.springframework.web.util.UriUtils
32
33 import org.openecomp.mso.bpmn.core.RollbackData
34 import org.openecomp.mso.bpmn.core.WorkflowException
35 import org.openecomp.mso.rest.APIResponse
36 import org.openecomp.mso.rest.RESTClient
37 import org.openecomp.mso.rest.RESTConfig
38
39 import org.w3c.dom.Document
40 import org.w3c.dom.Element
41 import org.w3c.dom.NamedNodeMap
42 import org.w3c.dom.Node
43 import org.w3c.dom.NodeList;
44 import org.xml.sax.InputSource
45
46
47
48 public class DoCreateVfModule extends VfModuleBase {
49
50         String Prefix="DCVFM_"
51         ExceptionUtil exceptionUtil = new ExceptionUtil()
52
53         /**
54          * Validates the request message and sets up the workflow.
55          * @param execution the execution
56          */
57         public void preProcessRequest(Execution execution) {
58                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
59                         'execution=' + execution.getId() +
60                         ')'
61                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
62                 logDebug('Entered ' + method, isDebugLogEnabled)
63
64                 execution.setVariable('prefix', Prefix)
65 try{
66                 String request = execution.getVariable("DoCreateVfModuleRequest")
67                 utils.logAudit("DoCreateVfModule request: " + request)
68
69                 def rollbackData = execution.getVariable("RollbackData")
70                 if (rollbackData == null) {
71                         rollbackData = new RollbackData()
72                 }
73
74                 execution.setVariable ("CreateAAIVfModuleRequest", request)
75                 execution.setVariable("DCVFM_vnfParamsExistFlag", false)
76                 //tenantId
77                 def tenantId = ""
78                 if (utils.nodeExists(request, "tenant-id")) {
79                         tenantId = utils.getNodeText(request, "tenant-id")
80                 }
81                 execution.setVariable("DCVFM_tenantId", tenantId)
82                 rollbackData.put("VFMODULE", "tenantid", tenantId)
83                 //volumeGroupId
84                 def volumeGroupId = ""
85                 if (utils.nodeExists(request, "volume-group-id")) {
86                         volumeGroupId = utils.getNodeText(request, "volume-group-id")
87                 }
88                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
89                 //volumeGroupId
90                 def volumeGroupName = ""
91                 if (utils.nodeExists(request, "volume-group-name")) {
92                         volumeGroupName = utils.getNodeText(request, "volume-group-name")
93                 }
94                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
95                 //cloudSiteId
96                 def cloudSiteId = ""
97                 if (utils.nodeExists(request, "aic-cloud-region")) {
98                         cloudSiteId = utils.getNodeText(request, "aic-cloud-region")
99                 }
100                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
101                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
102                 logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled)
103                 //vnfType
104                 def vnfType = ""
105                 if (utils.nodeExists(request, "vnf-type")) {
106                         vnfType = utils.getNodeText(request, "vnf-type")
107                 }
108                 execution.setVariable("DCVFM_vnfType", vnfType)
109                 rollbackData.put("VFMODULE", "vnftype", vnfType)
110                 logDebug("vnfType: " + vnfType, isDebugLogEnabled)
111                 //vnfName
112                 def vnfName = ""
113                 if (utils.nodeExists(request, "vnf-name")) {
114                         vnfName = utils.getNodeText(request, "vnf-name")
115                 }
116                 execution.setVariable("DCVFM_vnfName", vnfName)
117                 rollbackData.put("VFMODULE", "vnfname", vnfName)
118                 logDebug("vnfName: " + vnfName, isDebugLogEnabled)
119                 //vnfId
120                 def vnfId = ""
121                 if (utils.nodeExists(request, "vnf-id")) {
122                         vnfId = utils.getNodeText(request, "vnf-id")
123                 }
124                 execution.setVariable("DCVFM_vnfId", vnfId)
125                 rollbackData.put("VFMODULE", "vnfid", vnfId)
126                 logDebug("vnfId: " + vnfId, isDebugLogEnabled)
127                 //vfModuleName
128                 def vfModuleName = ""
129                 if (utils.nodeExists(request, "vf-module-name")) {
130                         vfModuleName = utils.getNodeText(request, "vf-module-name")
131                 }
132                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
133                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
134                 logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled)
135                 //vfModuleModelName
136                 def vfModuleModelName = ""
137                 if (utils.nodeExists(request, "vf-module-model-name")) {
138                         vfModuleModelName = utils.getNodeText(request, "vf-module-model-name")
139                 }
140                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
141                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
142                 logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled)
143                 //vfModuleId
144                 def vfModuleId = ""
145                 if (utils.nodeExists(request, "vf-module-id")) {
146                         vfModuleId = utils.getNodeText(request, "vf-module-id")
147                 }
148                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
149                 logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled)
150                 def requestId = ""
151                 if (utils.nodeExists(request, "request-id")) {
152                         requestId = utils.getNodeText(request, "request-id")
153                 }
154                 execution.setVariable("DCVFM_requestId", requestId)
155                 logDebug("requestId: " + requestId, isDebugLogEnabled)
156                 //serviceId
157                 def serviceId = ""
158                 if (utils.nodeExists(request, "service-id")) {
159                         serviceId = utils.getNodeText(request, "service-id")
160                 }
161                 execution.setVariable("DCVFM_serviceId", serviceId)
162                 logDebug("serviceId: " + serviceId, isDebugLogEnabled)
163                 //serviceInstanceId
164                 def serviceInstanceId = ""
165                 if (utils.nodeExists(request, "service-instance-id")) {
166                         serviceInstanceId = utils.getNodeText(request, "service-instance-id")
167                 }
168                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
169                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
170                 logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled)
171                 //source
172                 def source = ""
173                 if (utils.nodeExists(request, "source")) {
174                         source = utils.getNodeText(request, "source")
175                 }
176                 execution.setVariable("DCVFM_source", source)
177                 rollbackData.put("VFMODULE", "source", source)
178                 logDebug("source: " + source, isDebugLogEnabled)
179                 //backoutOnFailure
180                 NetworkUtils networkUtils = new NetworkUtils()
181                 def backoutOnFailure = networkUtils.isRollbackEnabled(execution,request)
182                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
183                 logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled)
184                 //isBaseVfModule
185                 def isBaseVfModule = "false"
186                 if (utils.nodeExists(request, "is-base-vf-module")) {
187                         isBaseVfModule = utils.getNodeText(request, "is-base-vf-module")
188                 }
189                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
190                 logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled)
191
192                 //asdcServiceModelVersion
193                 def asdcServiceModelVersion = ""
194                 if (utils.nodeExists(request, "asdc-service-model-version")) {
195                         asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version")
196                 }
197                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
198                 logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled)
199
200                 //Get or Generate UUID
201                 String uuid = execution.getVariable("DCVFM_uuid")
202                 if(uuid == null){
203                         uuid = UUID.randomUUID()
204                         logDebug("Generated messageId (UUID) is: " + uuid, isDebugLogEnabled)
205                 }else{
206                         logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled)
207                 }
208                 execution.setVariable("DCVFM_uuid", uuid)
209                 execution.setVariable("DCVFM_baseVfModuleId", "")
210                 execution.setVariable("DCVFM_baseVfModuleHeatStackId", "")
211                 execution.setVariable("DCVFM_heatStackId", "")
212                 execution.setVariable("DCVFM_contrailServiceInstanceFqdn", "")
213                 execution.setVariable("DCVFM_volumeGroupStackId", "")
214                 execution.setVariable("DCVFM_cloudRegionForVolume", "")
215                 rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false")
216                 rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false")
217                 rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false")
218                 rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "false")
219                 rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "false")
220                 rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false")
221
222                 String sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback')
223                         if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
224                                 def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing'
225                                 logError(msg)
226                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
227                         }
228                         execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl)
229                         utils.logAudit("SDNC Callback URL: " + sdncCallbackUrl)
230                     logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugLogEnabled)
231                         String vnfCallbackUrl = (String) execution.getVariable('URN_mso_workflow_vnfadapter_rest_callback')
232                         if (vnfCallbackUrl == null || vnfCallbackUrl.trim().isEmpty()) {
233                                 def msg = 'Required variable \'URN_mso_workflow_vnfadapter_rest_callback\' is missing'
234                                 logError(msg)
235                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
236                         }
237
238                 // Process the parameters
239
240                 String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params")
241                 if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
242                                 utils.log("DEBUG", "Request contains NO VNF Params", isDebugLogEnabled)
243                 }else{
244                                 utils.log("DEBUG", "Request does contain VNF Params", isDebugLogEnabled)
245                                 execution.setVariable("DCVFM_vnfParamsExistFlag", true)
246
247                                 InputSource xmlSource = new InputSource(new StringReader(request));
248                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
249                                 docFactory.setNamespaceAware(true)
250                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
251                                 Document xml = docBuilder.parse(xmlSource)
252                                 //Get params, build map
253                                 Map<String, String> paramsMap = new HashMap<String, String>()
254                                 NodeList paramsList = xml.getElementsByTagNameNS("*", "param")
255
256                                 for (int z = 0; z < paramsList.getLength(); z++) {
257                                         Node node = paramsList.item(z)
258                                         String paramValue = node.getTextContent()
259                                         NamedNodeMap e = node.getAttributes()
260                                         String paramName = e.getNamedItem("name").getTextContent()
261                                         paramsMap.put(paramName, paramValue)
262                                 }
263                                 execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
264                         }
265
266                 execution.setVariable("RollbackData", rollbackData)
267 }catch(BpmnError b){
268                         throw b
269 }catch(Exception e){
270         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
271 }
272
273                 logDebug('Exited ' + method, isDebugLogEnabled)
274         }
275
276         /**
277          * Validates a workflow response.
278          * @param execution the execution
279          * @param responseVar the execution variable in which the response is stored
280          * @param responseCodeVar the execution variable in which the response code is stored
281          * @param errorResponseVar the execution variable in which the error response is stored
282          */
283         public void validateWorkflowResponse(Execution execution, String responseVar,
284                         String responseCodeVar, String errorResponseVar) {
285                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
286                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
287         }
288
289
290         /**
291          * Sends the empty, synchronous response back to the API Handler.
292          * @param execution the execution
293          */
294         public void sendResponse(Execution execution) {
295                 def method = getClass().getSimpleName() + '.sendResponse(' +
296                         'execution=' + execution.getId() +
297                         ')'
298                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
299                 logDebug('Entered ' + method, isDebugLogEnabled)
300
301                 try {
302                         buildResponse(execution, "", 200)
303                         logDebug('Exited ' + method, isDebugLogEnabled)
304                 } catch (BpmnError e) {
305                         throw e;
306                 } catch (Exception e) {
307                         logError('Caught exception in ' + method, e)
308                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Internal Error')
309                 }
310         }
311
312         /**
313          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
314          * A 200 response is expected with the VNF info in the response body. Will find out the base module info
315          * and existing VNF's name for add-on modules
316          *
317          * @param execution The flow's execution instance.
318          */
319         public void postProcessCreateAAIVfModule(Execution execution) {
320                 def method = getClass().getSimpleName() + '.getVfModule(' +
321                         'execution=' + execution.getId() +
322                         ')'
323                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
324                 logDebug('Entered ' + method, isDebugLogEnabled)
325
326                 try {
327                         def createResponse = execution.getVariable('DCVFM_createVfModuleResponse')
328                         utils.logAudit("createVfModule Response: " + createResponse)
329
330                         def rollbackData = execution.getVariable("RollbackData")
331                         String vnfName = utils.getNodeText1(createResponse, 'vnf-name')
332                         if (vnfName != null) {
333                                 execution.setVariable('DCVFM_vnfName', vnfName)
334                                 logDebug("vnfName retrieved from AAI is: " + vnfName, isDebugLogEnabled)
335                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
336                         }
337                         String vnfId = utils.getNodeText1(createResponse, 'vnf-id')
338                         execution.setVariable('DCVFM_vnfId', vnfId)
339                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
340                         String vfModuleId = utils.getNodeText1(createResponse, 'vf-module-id')
341                         execution.setVariable('DCVFM_vfModuleId', vfModuleId)
342                         logDebug("vfModuleId is: " + vfModuleId, isDebugLogEnabled)
343                         rollbackData.put("VFMODULE", "vnfid", vnfId)
344                         rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId)
345                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true")
346                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true")
347                         execution.setVariable("RollbackData", rollbackData)
348                 } catch (Exception ex) {
349                                 ex.printStackTrace()
350                                 logDebug('Exception occurred while postProcessing CreateAAIVfModule request:' + ex.getMessage(),isDebugLogEnabled)
351                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage())
352                 }
353                 logDebug('Exited ' + method, isDebugLogEnabled)
354         }
355
356
357         /**
358          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
359          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
360          *
361          * @param execution The flow's execution instance.
362          */
363         public void queryAAIVfModule(Execution execution) {
364                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
365                 def method = getClass().getSimpleName() + '.getVfModule(' +
366                         'execution=' + execution.getId() +
367                         ')'
368                 logDebug('Entered ' + method, isDebugLogEnabled)
369
370                 try {
371                         def vnfId = execution.getVariable('DCVFM_vnfId')
372                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
373
374                         AaiUtil aaiUriUtil = new AaiUtil(this)
375                         String  aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
376                         logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
377
378                         String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8")
379                         utils.logAudit("AAI endPoint: " + endPoint)
380
381                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
382
383                         try {
384                                 RESTConfig config = new RESTConfig(endPoint);
385                                 def responseData = ''
386                                 def aaiRequestId = UUID.randomUUID().toString()
387                                 RESTClient client = new RESTClient(config).
388                                         addHeader('X-TransactionId', aaiRequestId).
389                                         addHeader('X-FromAppId', 'MSO').
390                                         addHeader('Content-Type', 'application/xml').
391                                         addHeader('Accept','application/xml');
392
393                                 if (basicAuthCred != null && !"".equals(basicAuthCred)) {
394                                         client.addAuthorizationHeader(basicAuthCred)
395                                 }
396
397                                 logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled)
398                                 APIResponse response = client.httpGet()
399                                 utils.logAudit("createVfModule - invoking httpGet() to AAI")
400
401                                 responseData = response.getResponseBodyAsString()
402                                 if (responseData != null) {
403                                         logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled)
404
405                                 }
406
407                                 utils.logAudit("createVfModule - queryAAIVfModule Response: " + responseData)
408                                 utils.logAudit("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode())
409
410                                 execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode())
411                                 execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
412                                 logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
413                                 logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
414                                 if (response.getStatusCode() == 200) {
415                                         // Parse the VNF record from A&AI to find base module info
416                                         logDebug('Parsing the VNF data to find base module info', isDebugLogEnabled)
417                                         if (responseData != null) {
418                                                 def vfModulesText = utils.getNodeXml(responseData, "vf-modules")
419                                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
420                                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
421                                                 int vfModulesSize = 0
422                                                 for (i in 0..vfModules.size()-1) {
423                                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
424                                                         def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module")
425
426                                                         if (isBaseVfModule == "true") {
427                                                             String baseModuleId = utils.getNodeText1(vfModuleXml, "vf-module-id")
428                                                             execution.setVariable("DCVFM_baseVfModuleId", baseModuleId)
429                                                             logDebug('Received baseVfModuleId: ' + baseModuleId, isDebugLogEnabled)
430                                                             String baseModuleHeatStackId = utils.getNodeText1(vfModuleXml, "heat-stack-id")
431                                                             execution.setVariable("DCVFM_baseVfModuleHeatStackId", baseModuleHeatStackId)
432                                                             logDebug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId, isDebugLogEnabled)
433                                                         }
434                                                 }
435                                         }
436                                 }
437                         } catch (Exception ex) {
438                                 ex.printStackTrace()
439                                 logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled)
440                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
441                         }
442                         logDebug('Exited ' + method, isDebugLogEnabled)
443                 } catch (BpmnError e) {
444                         throw e;
445                 } catch (Exception e) {
446                         logError('Caught exception in ' + method, e)
447                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage())
448                 }
449         }
450
451
452         public void preProcessSDNCAssignRequest(Execution execution){
453                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
454                 execution.setVariable("prefix", Prefix)
455                 logDebug(" ======== STARTED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled)
456                 def vnfId = execution.getVariable("DCVFM_vnfId")
457                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
458                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
459                 logDebug("NEW VNF ID: " + vnfId, isDebugLogEnabled)
460                 utils.logAudit("NEW VNF ID: " + vnfId)
461
462                 try{
463
464                         //Build SDNC Request
465
466                         def svcInstId = ""
467                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
468                                 svcInstId = vfModuleId
469                         }
470                         else {
471                                 svcInstId = serviceInstanceId
472                         }
473
474                         String assignSDNCRequest = buildSDNCRequest(execution, svcInstId, "assign")
475
476                         assignSDNCRequest = utils.formatXml(assignSDNCRequest)
477                         execution.setVariable("DCVFM_assignSDNCRequest", assignSDNCRequest)
478                         logDebug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest, isDebugLogEnabled)
479                         utils.logAudit("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest)
480
481                 }catch(Exception e){
482                         utils.log("ERROR", "Exception Occured Processing preProcessSDNCAssignRequest. Exception is:\n" + e, isDebugLogEnabled)
483                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage())
484                 }
485                 logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled)
486         }
487
488         public void preProcessSDNCGetRequest(Execution execution){
489                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
490                 execution.setVariable("prefix", Prefix)
491                 utils.log("DEBUG", " ======== STARTED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
492                 try{
493                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
494                         utils.logAudit("DCVFM_assignSDNCAdapterResponse is: \n" + response)
495
496                         String data = utils.getNodeXml(response, "response-data")
497                         data = data.replaceAll("&lt;", "<")
498                         data = data.replaceAll("&gt;", ">")
499                         String vnfId = utils.getNodeText1(data, "vnf-id")
500                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
501                         def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId')
502
503                         String uuid = execution.getVariable('testReqId') // for junits
504                         if(uuid==null){
505                                 uuid = execution.getVariable("att-mso-request-id") + "-" +      System.currentTimeMillis()
506                         }
507
508                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId
509                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
510                         utils.logAudit("callbackUrl:" + callbackUrl)
511
512                         def svcInstId = ""
513                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
514                                 svcInstId = vfModuleId
515                         }
516                         else {
517                                 svcInstId = serviceInstanceId
518                         }
519
520                         //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE
521                         sleep(5000)
522
523                         String SDNCGetRequest =
524                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://ecomp.att.com/mso/request/types/v1"
525                                                                                         xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1"
526                                                                                         xmlns:sdncadapter="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
527                                         <sdncadapter:RequestHeader>
528                                         <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
529                                         <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
530                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
531                                         <sdncadapter:SvcOperation>${serviceOperation}</sdncadapter:SvcOperation>
532                                         <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
533                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
534                                 </sdncadapter:RequestHeader>
535                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
536                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
537
538                         utils.logAudit("SDNCGetRequest: \n" + SDNCGetRequest)
539                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
540                         utils.log("DEBUG", "Outgoing GetSDNCRequest is: \n" + SDNCGetRequest, isDebugLogEnabled)
541
542                 }catch(Exception e){
543                         utils.log("ERROR", "Exception Occurred Processing preProcessSDNCGetRequest. Exception is:\n" + e, isDebugLogEnabled)
544                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
545                 }
546                 utils.log("DEBUG", "======== COMPLETED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
547         }
548
549
550         public void preProcessVNFAdapterRequest(Execution execution) {
551                 def method = getClass().getSimpleName() + '.VNFAdapterCreateVfModule(' +
552                         'execution=' + execution.getId() +
553                         ')'
554                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
555                 logDebug('Entered ' + method, isDebugLogEnabled)
556
557                 //def xml = execution.getVariable("DoCreateVfModuleRequest")
558                 //logDebug('VNF REQUEST is: ' + xml, isDebugLogEnabled)
559
560                 //Get variables
561                 //cloudSiteId
562                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
563                 //tenantId
564                 def tenantId = execution.getVariable("DCVFM_tenantId")
565                 //vnfType
566                 def vnfType = execution.getVariable("DCVFM_vnfType")
567                 //vnfName
568                 def vnfName = execution.getVariable("DCVFM_vnfName")
569                 //vnfId
570                 def vnfId = execution.getVariable("DCVFM_vnfId")
571                 //vfModuleName
572                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
573                 //vfModuleModelName
574                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
575                 //vfModuleId
576                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
577                 //requestId
578                 def requestId = execution.getVariable("DCVFM_requestId")
579                 //serviceId
580                 def serviceId = execution.getVariable("DCVFM_serviceId")
581                 //serviceInstanceId
582                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
583                 //backoutOnFailure
584                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
585                 //volumeGroupId
586                 def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
587                 // baseVfModuleId
588                 def baseVfModuleId = execution.getVariable("DCVFM_baseVfModuleId")
589                 // baseVfModuleStackId
590                 def baseVfModuleStackId = execution.getVariable("DCVFM_baseVfModuleHeatStackId")
591                 // asdcServiceModelVersion
592                 def asdcServiceModelVersion = execution.getVariable("DCVFM_asdcServiceModelVersion")
593                 //volumeGroupStackId
594                 def volumeGroupStackId = execution.getVariable("DCVFM_volumeGroupStackId")
595
596                 def messageId = execution.getVariable('att-mso-request-id') + '-' +
597                                 System.currentTimeMillis()
598
599                 def notificationUrl = execution.getVariable("URN_mso_workflow_vnfadapter_rest_callback")
600                 def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
601
602                 utils.logAudit("notificationUrl: " + notificationUrl)
603                 utils.logAudit("QualifiedHostName: " + useQualifiedHostName)
604
605                 if ('true'.equals(useQualifiedHostName)) {
606                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
607                 }
608
609                 String vnfParams
610                         if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
611                                 StringBuilder sbParams = new StringBuilder()
612                                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
613
614                                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
615                                         String paramsXml
616                                         String paramName = entry.getKey();
617                                         String paramValue = entry.getValue()
618                                         paramsXml =
619                                                         """     <entry>
620                                                         <key>${paramName}</key>
621                                                 <value>${paramValue}</value>
622                                                 </entry>
623                                         """
624
625                                         vnfParams = sbParams.append(paramsXml)
626                                 }
627                         }else{
628                                 vnfParams = ""
629                         }
630
631                 //Get SDNC Response Data for VnfSubCreate Request
632                 String sdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse')
633                 utils.logAudit("sdncGetResponse: " + sdncGetResponse)
634
635                 String vfModuleParams = buildVfModuleParams(vnfParams, sdncGetResponse, vnfId, vnfName,
636                                 vfModuleId, vfModuleName)
637
638                 def svcInstId = ""
639                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
640                                 svcInstId = serviceId
641                 }
642                 else {
643                         svcInstId = serviceInstanceId
644                 }
645
646
647                 def createVnfARequest = """
648                 <createVfModuleRequest>
649                 <cloudSiteId>${cloudSiteId}</cloudSiteId>
650                 <tenantId>${tenantId}</tenantId>
651                 <vnfId>${vnfId}</vnfId>
652                 <vnfName>${vnfName}</vnfName>
653                 <vfModuleName>${vfModuleName}</vfModuleName>
654                 <vfModuleId>${vfModuleId}</vfModuleId>
655                 <vnfType>${vnfType}</vnfType>
656                 <vfModuleType>${vfModuleModelName}</vfModuleType>
657                 <vnfVersion>${asdcServiceModelVersion}</vnfVersion>
658                 <requestType></requestType>
659                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
660         <volumeGroupStackId>${volumeGroupStackId}</volumeGroupStackId>
661         <baseVfModuleId>${baseVfModuleId}</baseVfModuleId>
662         <baseVfModuleStackId>${baseVfModuleStackId}</baseVfModuleStackId>
663         <skipAAI>true</skipAAI>
664         <backout>${backoutOnFailure}</backout>
665         <failIfExists>true</failIfExists>
666                 <vfModuleParams>
667                 ${vfModuleParams}
668                 </vfModuleParams>
669                 <msoRequest>
670                         <requestId>${requestId}</requestId>
671                         <serviceInstanceId>${svcInstId}</serviceInstanceId>
672                 </msoRequest>
673                 <messageId>${messageId}</messageId>
674                 <notificationUrl>${notificationUrl}</notificationUrl>
675                 </createVfModuleRequest>"""
676
677                 utils.logAudit("Create VfModule Request to VNF Adapter : " + createVnfARequest)
678                 logDebug("Create VfModule Request to VNF Adapter: " + createVnfARequest, isDebugLogEnabled)
679                 execution.setVariable("DCVFM_createVnfARequest", createVnfARequest)
680         }
681
682         /**
683          * Validates the request, request id and service instance id.  If a problem is found,
684          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
685          * method also sets up the log context for the workflow.
686          * @param execution the execution
687          * @return the validated request
688          */
689         public String validateInfraRequest(Execution execution) {
690                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
691                         'execution=' + execution.getId() +
692                         ')'
693                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
694                 logDebug('Entered ' + method, isDebugLogEnabled)
695
696                 String processKey = getProcessKey(execution);
697                 def prefix = execution.getVariable("prefix")
698
699                 if (prefix == null) {
700                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
701                 }
702
703                 try {
704                         def request = execution.getVariable(prefix + 'Request')
705
706                         if (request == null) {
707                                 request = execution.getVariable(processKey + 'Request')
708
709                                 if (request == null) {
710                                         request = execution.getVariable('bpmnRequest')
711                                 }
712
713                                 setVariable(execution, processKey + 'Request', null);
714                                 setVariable(execution, 'bpmnRequest', null);
715                                 setVariable(execution, prefix + 'Request', request);
716                         }
717
718                         if (request == null) {
719                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
720                         }
721                         utils.logAudit("DoCreateVfModule Request: " + request)
722
723                         /*
724
725                         def requestId = execution.getVariable("att-mso-request-id")
726
727                         if (requestId == null) {
728                                 createWorkflowException(execution, 1002, processKey + " request has no att-mso-request-id")
729                         }
730
731                         def serviceInstanceId = execution.getVariable("att-mso-service-instance-id")
732
733                         if (serviceInstanceId == null) {
734                                 createWorkflowException(execution, 1002, processKey + " request message has no att-mso-service-instance-id")
735                         }
736
737                         utils.logContext(requestId, serviceInstanceId)
738                         */
739                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
740                         logDebug('Exited ' + method, isDebugLogEnabled)
741                         return request
742                 } catch (BpmnError e) {
743                         throw e;
744                 } catch (Exception e) {
745                         logError('Caught exception in ' + method, e)
746                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
747                 }
748         }
749
750         public boolean isVolumeGroupIdPresent(Execution execution) {
751
752                 def method = getClass().getSimpleName() + '.isVolumeGroupIdPresent(' +
753                         'execution=' + execution.getId() +
754                         ')'
755                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
756                 logDebug('Entered ' + method, isDebugLogEnabled)
757
758                 def request = execution.getVariable('DoCreateVfModuleRequest')
759                 String volumeGroupId = utils.getNodeText1(request, "volume-group-id")
760                 if (volumeGroupId == null || volumeGroupId.isEmpty()) {
761                         logDebug('No volume group id is present', isDebugLogEnabled)
762                         return false
763                 }
764                 else {
765                         logDebug('Volume group id is present', isDebugLogEnabled)
766                         return true
767                 }
768
769         }
770
771         public boolean isVolumeGroupNamePresent(Execution execution) {
772
773                 def method = getClass().getSimpleName() + '.isVolumeGroupNamePresent(' +
774                         'execution=' + execution.getId() +
775                         ')'
776                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
777                 logDebug('Entered ' + method, isDebugLogEnabled)
778
779                 def request = execution.getVariable('DoCreateVfModuleRequest')
780                 String volumeGroupName = utils.getNodeText1(request, "volume-group-name")
781                 if (volumeGroupName == null || volumeGroupName.isEmpty()) {
782                         logDebug('No volume group name is present', isDebugLogEnabled)
783                         return false
784                 }
785                 else {
786                         logDebug('Volume group name is present', isDebugLogEnabled)
787                         return true
788                 }
789
790         }
791
792         public String buildSDNCRequest(Execution execution, String svcInstId, String action){
793
794                 String uuid = execution.getVariable('testReqId') // for junits
795                 if(uuid==null){
796                         uuid = execution.getVariable("att-mso-request-id") + "-" +      System.currentTimeMillis()
797                 }
798                 def callbackURL = execution.getVariable("DCVFM_sdncCallbackUrl")
799                 def requestId = execution.getVariable("DCVFM_requestId")
800                 def serviceId = execution.getVariable("DCVFM_serviceId")
801                 def vnfType = execution.getVariable("DCVFM_vnfType")
802                 def vnfName = execution.getVariable("DCVFM_vnfName")
803                 def tenantId = execution.getVariable("DCVFM_tenantId")
804                 def source = execution.getVariable("DCVFM_source")
805                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
806                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
807                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
808                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
809                 def vnfId = execution.getVariable("DCVFM_vnfId")
810                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
811
812                 String sdncVNFParamsXml = ""
813
814                 if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
815                         sdncVNFParamsXml = buildSDNCParamsXml(execution)
816                 }else{
817                         sdncVNFParamsXml = ""
818                 }
819
820                 String sdncRequest =
821                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://ecomp.att.com/mso/request/types/v1"
822                                                                                                         xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1"
823                                                                                                         xmlns:sdncadapter="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
824            <sdncadapter:RequestHeader>
825                                 <sdncadapter:RequestId>${requestId}</sdncadapter:RequestId>
826                                 <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
827                                 <sdncadapter:SvcAction>${action}</sdncadapter:SvcAction>
828                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
829                                 <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
830                 </sdncadapter:RequestHeader>
831         <sdncadapterworkflow:SDNCRequestData>
832                 <request-information>
833                         <request-id>${requestId}</request-id>
834                         <request-action>VNFActivateRequest</request-action>
835                         <source>${source}</source>
836                         <notification-url/>
837                 </request-information>
838                 <service-information>
839                         <service-id>${serviceId}</service-id>
840                         <service-type>${serviceId}</service-type>
841                         <service-instance-id>${svcInstId}</service-instance-id>
842                         <subscriber-name>notsurewecare</subscriber-name>
843                 </service-information>
844                 <vnf-request-information>
845                         <vnf-id>${vfModuleId}</vnf-id>
846                         <vnf-type>${vfModuleModelName}</vnf-type>
847                         <vnf-name>${vfModuleName}</vnf-name>
848                         <generic-vnf-id>${vnfId}</generic-vnf-id>
849                         <generic-vnf-name>${vnfName}</generic-vnf-name>
850                         <generic-vnf-type>${vnfType}</generic-vnf-type>
851                         <aic-cloud-region>${cloudSiteId}</aic-cloud-region>
852                         <tenant>${tenantId}</tenant>
853                 ${sdncVNFParamsXml}
854                 </vnf-request-information>
855         </sdncadapterworkflow:SDNCRequestData>
856         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
857
858         utils.logAudit("sdncRequest:  " + sdncRequest)
859         return sdncRequest
860
861         }
862
863         public void preProcessSDNCActivateRequest(Execution execution) {
864                 def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
865                         'execution=' + execution.getId() +
866                         ')'
867                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
868                 logDebug('Entered ' + method, isDebugLogEnabled)
869                 execution.setVariable("prefix", Prefix)
870                 logDebug(" ======== STARTED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled)
871                 try{
872                         String vnfId = execution.getVariable("DCVFM_vnfId")
873                         String vfModuleId = execution.getVariable("DCVFM_vfModuleId")
874                         String serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
875
876                         def svcInstId = ""
877                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
878                                 svcInstId = vfModuleId
879                         }
880                         else {
881                                 svcInstId = serviceInstanceId
882                         }
883                         String activateSDNCRequest = buildSDNCRequest(execution, svcInstId, "activate")
884
885                         execution.setVariable("DCVFM_activateSDNCRequest", activateSDNCRequest)
886                         logDebug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest, isDebugLogEnabled)
887                         utils.logAudit("Outgoing CommitSDNCRequest is: \n"  + activateSDNCRequest)
888
889                 }catch(Exception e){
890                         log.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e, isDebugLogEnabled)
891                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
892                 }
893                 logDebug("======== COMPLETED  preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled)
894         }
895
896         public void postProcessVNFAdapterRequest(Execution execution) {
897                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
898                         'execution=' + execution.getId() +
899                         ')'
900                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
901                 logDebug('Entered ' + method, isDebugLogEnabled)
902                 execution.setVariable("prefix",Prefix)
903                 try{
904                 logDebug(" *** STARTED postProcessVNFAdapterRequest Process*** ", isDebugLogEnabled)
905
906                 String vnfResponse = execution.getVariable("DCVFM_createVnfAResponse")
907                 logDebug("VNF Adapter Response is: " + vnfResponse, isDebugLogEnabled)
908                 utils.logAudit("createVnfAResponse is: \n"  + vnfResponse)
909
910                 RollbackData rollbackData = execution.getVariable("RollbackData")
911                 if(vnfResponse != null){
912
913                         if(vnfResponse.contains("createVfModuleResponse")){
914                                 logDebug("Received a Good Response from VNF Adapter for CREATE_VF_MODULE Call.", isDebugLogEnabled)
915                                 execution.setVariable("DCVFM_vnfVfModuleCreateCompleted", true)
916                                 String heatStackId = utils.getNodeText1(vnfResponse, "vfModuleStackId")
917                                 execution.setVariable("DCVFM_heatStackId", heatStackId)
918                                 logDebug("Received heat stack id from VNF Adapter: " + heatStackId, isDebugLogEnabled)
919                                 rollbackData.put("VFMODULE", "heatstackid", heatStackId)
920                                 // Parse vnfOutputs for network_fqdn
921                                 if (vnfResponse.contains("vfModuleOutputs")) {
922                                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
923                                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
924                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
925                         docFactory.setNamespaceAware(true)
926                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
927                         Document outputsXml = docBuilder.parse(source)
928
929                                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
930                                         for (int i = 0; i< entries.getLength(); i++) {
931                                                 Node node = entries.item(i)
932                                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
933                                                         Element element = (Element) node
934                                                         String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
935                                                         if (key.equals("contrail-service-instance-fqdn")) {
936                                                                 String contrailServiceInstanceFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
937                                                                 logDebug("Obtained contrailServiceInstanceFqdn: " + contrailServiceInstanceFqdn, isDebugLogEnabled)
938                                                                 execution.setVariable("DCVFM_contrailServiceInstanceFqdn", contrailServiceInstanceFqdn)
939                                                         }
940                                                 }
941                                         }
942                                 }
943                         }else{
944                                 logDebug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.", isDebugLogEnabled)
945                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
946                         }
947                 }else{
948                         logDebug("Response from VNF Adapter is Null for CREATE_VF_MODULE Call.", isDebugLogEnabled)
949                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
950                 }
951
952                 rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true")
953                 execution.setVariable("RollbackData", rollbackData)
954
955                 }catch(BpmnError b){
956                         throw b
957                 }catch(Exception e){
958                         logDebug("Internal Error Occured in PostProcess Method", isDebugLogEnabled)
959                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
960                 }
961                 logDebug(" *** COMPLETED postProcessVnfAdapterResponse Process*** ", isDebugLogEnabled)
962         }
963
964
965         public void preProcessUpdateAAIVfModuleRequestOrch(Execution execution) {
966                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestOrch(' +
967                         'execution=' + execution.getId() +
968                         ')'
969                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
970                 logDebug('Entered ' + method, isDebugLogEnabled)
971                 execution.setVariable("prefix", Prefix)
972                 logDebug(" ======== STARTED preProcessUpdateAAIVfModuleRequestOrch ======== ", isDebugLogEnabled)
973
974                 try{
975
976                         //Build UpdateAAIVfModule Request
977                         boolean setContrailServiceInstanceFqdn = false
978                         def contrailServiceInstanceFqdn = execution.getVariable("DCVFM_contrailServiceInstanceFqdn")
979                         if (!contrailServiceInstanceFqdn.equals("")) {
980                                 setContrailServiceInstanceFqdn = true
981                         }
982
983                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, true, setContrailServiceInstanceFqdn)
984
985                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
986                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
987                         logDebug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest, isDebugLogEnabled)
988                         utils.logAudit("Outgoing UpdateAAIVfModuleRequest is: \n"  + updateAAIVfModuleRequest)
989
990                 }catch(Exception e){
991                         utils.log("ERROR", "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch. Exception is:\n" + e, isDebugLogEnabled)
992                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage())
993                 }
994                 logDebug("======== COMPLETED preProcessUpdateAAIVfModuleRequestOrch ======== ", isDebugLogEnabled)
995
996         }
997
998         public void preProcessUpdateAAIVfModuleRequestGroup(Execution execution) {
999                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestGroup(' +
1000                         'execution=' + execution.getId() +
1001                         ')'
1002                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1003                 logDebug('Entered ' + method, isDebugLogEnabled)
1004                 execution.setVariable("prefix", Prefix)
1005                 logDebug(" ======== STARTED preProcessUpdateAAIVfModuleRequestGroup ======== ", isDebugLogEnabled)
1006
1007                 try{
1008
1009                         //Build UpdateAAIVfModule Request
1010
1011                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, true, false, false, false)
1012
1013                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1014                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1015                         logDebug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest, isDebugLogEnabled)
1016                         utils.logAudit("Outgoing UpdateAAIVfModuleRequest is: \n"  + updateAAIVfModuleRequest)
1017
1018                 }catch(Exception e){
1019                         utils.log("ERROR", "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup. Exception is:\n" + e, isDebugLogEnabled)
1020                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage())
1021                 }
1022                 logDebug("======== COMPLETED  preProcessUpdateAAIVfModuleRequestGroup ======== ", isDebugLogEnabled)
1023
1024         }
1025
1026         public void validateSDNCResponse(Execution execution, String response, String method){
1027                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
1028                 execution.setVariable("prefix",Prefix)
1029                 logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled)
1030
1031                 WorkflowException workflowException = execution.getVariable("WorkflowException")
1032                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1033
1034                 utils.logAudit("workflowException: " + workflowException)
1035
1036                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1037                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1038
1039                 utils.logAudit("SDNCResponse: " + response)
1040
1041                 String sdncResponse = response
1042                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
1043                         logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse, isDebugLogEnabled)
1044                         RollbackData rollbackData = execution.getVariable("RollbackData")
1045
1046                         if(method.equals("assign")){
1047                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "true")
1048                                 execution.setVariable("CRTGVNF_sdncAssignCompleted", true)
1049                         }
1050                         else if (method.equals("activate")) {
1051                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true")
1052                         }
1053                         execution.setVariable("RollbackData", rollbackData)
1054                 }else{
1055                         logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled)
1056                         throw new BpmnError("MSOWorkflowException")
1057                 }
1058                 logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled)
1059         }
1060
1061         public void preProcessUpdateAfterCreateRequest(Execution execution){
1062                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
1063                 execution.setVariable("prefix", Prefix)
1064                 utils.log("DEBUG", " ======== STARTED preProcessRequest Process ======== ", isDebugLogEnabled)
1065                 try{
1066                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
1067                         utils.logAudit("DCVFM_assignSDNCAdapterResponse: " + response)
1068
1069                         String data = utils.getNodeXml(response, "response-data")
1070                         data = data.replaceAll("&lt;", "<")
1071                         data = data.replaceAll("&gt;", ">")
1072                         String vnfId = utils.getNodeText1(data, "vnf-id")
1073
1074                         String uuid = execution.getVariable('testReqId') // for junits
1075                         if(uuid==null){
1076                                 uuid = execution.getVariable("att-mso-request-id") + "-" +      System.currentTimeMillis()
1077                         }
1078
1079                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vnfId
1080                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
1081                         utils.logAudit("callbackUrl: " + callbackUrl)
1082
1083                         String SDNCGetRequest =
1084                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://ecomp.att.com/mso/request/types/v1"
1085                                                                                         xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1"
1086                                                                                         xmlns:sdncadapter="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
1087                                         <sdncadapter:RequestHeader>
1088                                         <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
1089                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
1090                                         <sdncadapter:SvcOperation>${serviceOperation}</sdncadapter:SvcOperation>
1091                                         <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
1092                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
1093                                 </sdncadapter:RequestHeader>
1094                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
1095                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1096
1097                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
1098                         utils.log("DEBUG", "Outgoing GetSDNCRequest is: \n" + SDNCGetRequest, isDebugLogEnabled)
1099                         utils.logAudit("Outgoing GetSDNCRequest: " + SDNCGetRequest)
1100
1101                 }catch(Exception e){
1102                         utils.log("ERROR", "Exception Occured Processing preProcessSDNCGetRequest. Exception is:\n" + e, isDebugLogEnabled)
1103                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
1104                 }
1105                 utils.log("DEBUG", "======== COMPLETED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
1106         }
1107
1108         public String buildUpdateAAIVfModuleRequest(Execution execution, boolean updateVolumeGroupId,
1109                 boolean updateOrchestrationStatus, boolean updateHeatStackId, boolean updateContrailFqdn){
1110
1111                 def vnfId = execution.getVariable("DCVFM_vnfId")
1112                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1113                 def volumeGroupIdString = ""
1114                 if (updateVolumeGroupId) {
1115                         volumeGroupIdString = "<volume-group-id>" + execution.getVariable("DCVFM_volumeGroupId") +
1116                                         "</volume-group-id>"
1117                 }
1118                 def orchestrationStatusString = ""
1119                 if (updateOrchestrationStatus) {
1120                         orchestrationStatusString = "<orchestration-status>Created</orchestration-status>"
1121                 }
1122                 def heatStackIdString = ""
1123                 if (updateHeatStackId) {
1124                         heatStackIdString = "<heat-stack-id>" + execution.getVariable("DCVFM_heatStackId") + "</heat-stack-id>"
1125                 }
1126                 def contrailFqdnString = ""
1127                 if (updateContrailFqdn) {
1128                         contrailFqdnString = "<contrail-service-instance-fqdn>" + execution.getVariable("DCVFM_contrailServiceInstanceFqdn") +
1129                                 "</contrail-service-instance-fqdn>"
1130                 }
1131
1132                 String updateAAIVfModuleRequest =
1133                         """<UpdateAAIVfModuleRequest>
1134                                 <vnf-id>${vnfId}</vnf-id>
1135                                 <vf-module-id>${vfModuleId}</vf-module-id>
1136                                 ${heatStackIdString}
1137                                 ${orchestrationStatusString}
1138                                 ${volumeGroupIdString}
1139                                 ${contrailFqdnString}
1140                         </UpdateAAIVfModuleRequest>"""
1141
1142         utils.logAudit("updateAAIVfModule Request: " + updateAAIVfModuleRequest)
1143         return updateAAIVfModuleRequest
1144
1145         }
1146
1147         public String buildSDNCParamsXml(Execution execution){
1148
1149                 String params = ""
1150                 StringBuilder sb = new StringBuilder()
1151                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1152
1153                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1154                         String paramsXml
1155                         String key = entry.getKey();
1156                         if(key.endsWith("_network")){
1157                                 String requestKey = key.substring(0, key.indexOf("_network"))
1158                                 String requestValue = entry.getValue()
1159                                 paramsXml =
1160 """<vnf-networks>
1161         <network-role>{ functx:substring-before-match(data($param/@name), '_network') }</network-role>
1162         <network-name>{ $param/text() }</network-name>
1163 </vnf-networks>"""
1164                         }else{
1165                         paramsXml = ""
1166                         }
1167                         params = sb.append(paramsXml)
1168                 }
1169                 return params
1170         }
1171
1172    public void queryCloudRegion (Execution execution) {
1173                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
1174                 execution.setVariable("prefix", Prefix)
1175                 utils.log("DEBUG", " ======== STARTED queryCloudRegion ======== ", isDebugLogEnabled)
1176
1177                 try {
1178                         String cloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1179
1180                         // Prepare AA&I url
1181                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
1182                         AaiUtil aaiUtil = new AaiUtil(this)
1183                         String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution)
1184                         String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion
1185                         utils.logAudit("CloudRegion Request: " + queryCloudRegionRequest)
1186
1187                         execution.setVariable("DCVFM_queryCloudRegionRequest", queryCloudRegionRequest)
1188                         utils.log("DEBUG", "DCVFM_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugLogEnabled)
1189
1190                         cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion)
1191
1192                         if ((cloudRegion != "ERROR")) {
1193                                 if(execution.getVariable("DCVFM_queryCloudRegionReturnCode") == "404"){
1194                                         execution.setVariable("DCVFM_cloudRegionForVolume", "AAIAIC25")
1195                                 }else{
1196                                 execution.setVariable("DCVFM_cloudRegionForVolume", cloudRegion)
1197                                 }
1198                                 execution.setVariable("DCVFM_isCloudRegionGood", true)
1199                         } else {
1200                                 String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable("DCVFM_queryCloudRegionReturnCode")
1201                                 utils.log("DEBUG", errorMessage, isDebugLogEnabled)
1202                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1203                                 execution.setVariable("DCVFM_isCloudRegionGood", false)
1204                         }
1205                         utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood"), isDebugLogEnabled)
1206
1207                 } catch(BpmnError b){
1208                         utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugLogEnabled)
1209                         throw b
1210                 }catch (Exception ex) {
1211                         // try error
1212                         String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage()
1213                         utils.log("ERROR", " AAI Query Cloud Region Failed.  Exception - " + "\n" + errorMessage, isDebugLogEnabled)
1214                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method")
1215                 }
1216         }
1217
1218    /**
1219     *This method occurs when an MSOWorkflowException is caught.  It logs the
1220     *variables and ensures that the "WorkflowException" Variable is set.
1221     *
1222     */
1223    public void processBPMNException(Execution execution){
1224            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1225            execution.setVariable("prefix",Prefix)
1226            try{
1227                    utils.log("DEBUG", "Caught a BPMN Exception", isDebugEnabled)
1228                    utils.log("DEBUG", "Started processBPMNException Method", isDebugEnabled)
1229                    utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
1230                    if(execution.getVariable("WorkflowException") == null){
1231                            exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during DoCreateVfModule Sub Process")
1232                    }
1233
1234            }catch(Exception e){
1235                    utils.log("DEBUG", "Caught Exception during processBPMNException Method: " + e, isDebugEnabled)
1236            }
1237            utils.log("DEBUG", "Completed processBPMNException Method", isDebugEnabled)
1238    }
1239
1240    public void prepareCreateAAIVfModuleVolumeGroupRequest(Execution execution) {
1241                 def method = getClass().getSimpleName() + '.prepareCreateAAIVfModuleVolumeGroupRequest(' +
1242                         'execution=' + execution.getId() +
1243                         ')'
1244                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1245                 logDebug('Entered ' + method, isDebugLogEnabled)
1246                 execution.setVariable("prefix", Prefix)
1247                 logDebug(" ======== STARTED prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled)
1248
1249                 try{
1250
1251                         //Build CreateAAIVfModuleVolumeGroup Request
1252
1253                         def vnfId = execution.getVariable("DCVFM_vnfId")
1254                         def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1255                         def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
1256                         //def aicCloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1257                         def aicCloudRegion = execution.getVariable("DCVFM_cloudRegionForVolume")
1258                         String createAAIVfModuleVolumeGroupRequest =
1259                         """<CreateAAIVfModuleVolumeGroupRequest>
1260                                 <vnf-id>${vnfId}</vnf-id>
1261                                 <vf-module-id>${vfModuleId}</vf-module-id>
1262                                 <volume-group-id>${volumeGroupId}</volume-group-id>
1263                                 <aic-cloud-region>${aicCloudRegion}</aic-cloud-region>
1264                         </CreateAAIVfModuleVolumeGroupRequest>"""
1265
1266                         createAAIVfModuleVolumeGroupRequest = utils.formatXml(createAAIVfModuleVolumeGroupRequest)
1267                         execution.setVariable("DCVFM_createAAIVfModuleVolumeGroupRequest", createAAIVfModuleVolumeGroupRequest)
1268                         logDebug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest, isDebugLogEnabled)
1269                         utils.logAudit("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n"  + createAAIVfModuleVolumeGroupRequest)
1270
1271                 }catch(Exception e){
1272                         utils.log("ERROR", "Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest. Exception is:\n" + e, isDebugLogEnabled)
1273                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage())
1274                 }
1275                 logDebug("======== COMPLETED  prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled)
1276
1277         }
1278
1279
1280 }
1281