Merge "updated ARIA version"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoCreateVfModuleVolumeV1.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 static org.camunda.spin.Spin.XML
24
25 import org.apache.commons.lang3.*
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.runtime.Execution
28 import org.openecomp.mso.bpmn.common.scripts.AaiUtil
29 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
30 import org.openecomp.mso.bpmn.common.scripts.NetworkUtils
31 import org.openecomp.mso.bpmn.common.scripts.VfModuleBase
32 import org.openecomp.mso.bpmn.core.WorkflowException
33 import org.openecomp.mso.rest.APIResponse
34 import org.springframework.web.util.UriUtils
35
36 class DoCreateVfModuleVolumeV1 extends VfModuleBase {
37         
38         String prefix='DCVFMODVOLV1_'
39         
40         
41         /**
42          * Perform initial processing, such as request validation, initialization of variables, etc.
43          * * @param execution
44          */
45         public void preProcessRequest (Execution execution) {
46                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
47                 preProcessRequest(execution, isDebugEnabled)
48         }
49         
50         /**
51          * Perform initial processing, such as request validation, initialization of variables, etc.
52          * @param execution
53          * @param isDebugEnabled
54          */
55         public void preProcessRequest (Execution execution, isDebugEnabled) {
56
57                 execution.setVariable("prefix",prefix)
58                 execution.setVariable(prefix+'SuccessIndicator', false)
59                 
60         
61                 // INPUT: DoCreateVfModuleVolumeV1Request, mso-request-id, volume-group-id, vnf-id, is-vid-request
62                 // OUTPUT: DCVFMODVOLV1_SuccessIndicator. WorkflowException
63                 
64                 def volumeRequest  = getVariable(execution, 'DoCreateVfModuleVolumeV1Request')
65                 if (volumeRequest != null) {
66                         execution.setVariable(prefix+'Request', volumeRequest)
67                 } else {        
68                         volumeRequest  = getVariable(execution, prefix+'Request')
69                         if (volumeRequest == null) {
70                                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'DoCreateVfModuleVolumeV1 received null request.')
71                         }
72                 }
73                 
74                 def vnfId = execution.getVariable('vnf-id')
75                 if (vnfId == null) {
76                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'DoCreateVfModuleVolumeV1 received null vnf-id.')
77                 }
78                 
79                 def volumeGroupId = execution.getVariable('volume-group-id')
80                 if (volumeGroupId == null) {
81                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'DoCreateVfModuleVolumeV1 received null volume-group-id.')
82                 }
83                 
84                 def requestId = execution.getVariable("mso-request-id")
85                 if (requestId == null || requestId == "") {
86                         requestId = utils.getNodeText1(volumeRequest, "request-id")
87                 }
88
89                 //def serviceId = execution.getVariable("mso-service-instance-id")
90                 //if (serviceId == null || serviceId == "") {
91                 def     serviceId = utils.getNodeText1(volumeRequest, "service-id")
92                 //}
93                 
94                 def source = utils.getNodeText1(volumeRequest, "source")
95                 
96                 execution.setVariable(prefix+'requestId', requestId)
97                 execution.setVariable(prefix+'serviceId', serviceId)
98                 execution.setVariable(prefix+'source', source)
99                 
100                 // @TODO: for better tracking of logs, should we strip all new lines in the log message?
101                 utils.logAudit('Incoming request: ' + volumeRequest)
102
103                 // Rollback settings
104                 NetworkUtils networkUtils = new NetworkUtils()
105                 def rollbackEnabled = networkUtils.isRollbackEnabled(execution,volumeRequest)
106                 execution.setVariable(prefix+"rollbackEnabled", rollbackEnabled)
107                 utils.log("DEBUG", 'rollbackEnabled: ' + rollbackEnabled, isDebugEnabled)
108                 
109         }
110         
111
112         /**
113          * Get cloud region
114          * @param execution
115          * @param isDebugEnabled
116          */
117         public void callRESTQueryAAICloudRegion (Execution execution, isDebugEnabled) {
118                 
119                 def request = execution.getVariable(prefix+'Request')
120                 def cloudRegion = utils.getNodeText1(request, "aic-cloud-region")
121                 utils.log("DEBUG", 'Request cloud region is: ' + cloudRegion, isDebugEnabled)
122
123                 AaiUtil aaiUtil = new AaiUtil(this)
124                 String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution)
125                 String queryCloudRegionRequest = aaiEndpoint + '/' + cloudRegion
126                 
127                 utils.logAudit(queryCloudRegionRequest)
128
129                 cloudRegion = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "PO", cloudRegion)
130
131                 if ((cloudRegion != "ERROR")) {
132                         if(execution.getVariable(prefix+"queryCloudRegionReturnCode") == "404"){
133                                 cloudRegion = "AAIAIC25"
134                         }
135                         execution.setVariable(prefix+"aicCloudRegion", cloudRegion)
136                         utils.log("DEBUG", "AIC Cloud Region: " + cloudRegion, isDebugEnabled)
137                 } else {
138                         String errorMessage = "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable(prefix+"queryCloudRegionReturnCode")
139                         utils.log("DEBUG", errorMessage, isDebugEnabled)
140                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, errorMessage)
141                 }
142         }
143         
144
145         /**
146          * Query AAI volume group by name
147          * @param execution
148          * @param isDebugEnabled
149          */
150         public void callRESTQueryAAIVolGrpName(Execution execution, isDebugEnabled) {
151
152                 def volumeRequest = execution.getVariable(prefix+'Request')
153                 def volumeGroupName = utils.getNodeText(volumeRequest, "volume-group-name")
154                 def cloudRegion = execution.getVariable(prefix+"aicCloudRegion")
155                 
156                 // Save volume group name
157                 execution.setVariable(prefix+'volumeGroupName', volumeGroupName)
158                 
159                 // This is for stub testing
160                 def testVolumeGroupName = execution.getVariable('test-volume-group-name')
161                 if (testVolumeGroupName != null && testVolumeGroupName.length() > 0) {
162                         volumeGroupName = testVolumeGroupName
163                         //reset to null
164                         execution.setVariable('test-volume-group-name', null)
165                 }
166                 
167                 AaiUtil aaiUtil = new AaiUtil(this)
168                 String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution)
169                 String queryAAIVolumeNameRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups" + "?volume-group-name=" + UriUtils.encode(volumeGroupName, 'UTF-8')
170
171                 utils.logAudit('Query AAI volume group by name: ' + queryAAIVolumeNameRequest)
172                 
173                 APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeNameRequest)
174                 
175                 String returnCode = response.getStatusCode()
176                 String aaiResponseAsString = response.getResponseBodyAsString()
177                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
178                 
179                 utils.logAudit("AAI query volume group by name return code: " + returnCode)
180                 utils.logAudit("AAI query volume group by name response: " + aaiResponseAsString)
181
182                 ExceptionUtil exceptionUtil = new ExceptionUtil()
183
184                 execution.setVariable(prefix+"queryAAIVolGrpNameResponse", aaiResponseAsString)
185                 execution.setVariable(prefix+'AaiReturnCode', returnCode)
186
187                 if (returnCode=='200') {
188                         // @TODO: verify error code
189                         // @TODO: create class of literals representing error codes
190                         execution.setVariable(prefix+'queryAAIVolGrpNameResponse', aaiResponseAsString)
191                         utils.log("DEBUG", "Volume Group Name $volumeGroupName exists in AAI.", isDebugEnabled)
192                 } else {
193                         if (returnCode=='404') {
194                                 utils.log("DEBUG", "Volume Group Name $volumeGroupName does not exist in AAI.", isDebugEnabled)
195                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupName not found in AAI. Response code: 404")
196                         } else {
197                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
198                                 throw new BpmnError("MSOWorkflowException")
199                         }
200                 }
201         }
202         
203
204         /**
205          * Create a WorkflowException 
206          * @param execution
207          * @param isDebugEnabled
208          */
209         public void buildWorkflowException(Execution execution, int errorCode, errorMessage, isDebugEnabled) {
210                 utils.log("DEBUG", errorMessage, isDebugEnabled)
211                 (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage)
212         }
213         
214
215         /**
216          * Create a WorkflowException
217          * @param execution
218          * @param isDebugEnabled
219          */
220         public void handleError(Execution execution, isDebugEnabled) {
221                 WorkflowException we = execution.getVariable('WorkflowException')
222                 if (we == null) {
223                         (new ExceptionUtil()).buildWorkflowException(execution, 2500, "Enexpected error encountered!")
224                 }
225                 throw new BpmnError("MSOWorkflowException")
226         }
227         
228         /**
229          * Create volume group in AAI
230          * @param execution
231          * @param isDebugEnabled
232          */
233         public void callRESTCreateAAIVolGrpName(Execution execution, isDebugEnabled) {
234
235                 def volumeRequest  = execution.getVariable(prefix+'Request')
236                 def vnfId = execution.getVariable('vnf-id')
237                 def volumeName = utils.getNodeText(volumeRequest, "volume-group-name")
238                 def modelCustomizationId = getNodeTextForce(volumeRequest, "model-customization-id")
239                 
240                 def cloudRegion = execution.getVariable(prefix+"aicCloudRegion")
241                 def groupId = execution.getVariable('volume-group-id')
242                 utils.log("DEBUG", "volume group id: " + groupId, isDebugEnabled)
243                 
244                 AaiUtil aaiUtil = new AaiUtil(this)
245                 String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution)
246                 String createAAIVolumeGrpNameUrlRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups/volume-group/" + UriUtils.encode(groupId, "UTF-8")
247                 
248                 String namespace =  aaiUtil.getNamespaceFromUri(aaiUtil.getCloudInfrastructureCloudRegionUri(execution))
249                 utils.log("DEBUG", "AAI namespace is: " + namespace, isDebugEnabled)
250                 
251                 utils.logAudit(createAAIVolumeGrpNameUrlRequest)
252                 
253                 //Prepare payload (PUT)
254                 def vnfType = utils.getNodeText(volumeRequest, "vnf-type")
255                 def tenantId = utils.getNodeText(volumeRequest, "tenant-id")
256                 
257                 NetworkUtils networkUtils = new NetworkUtils()
258                 String payload = networkUtils.createCloudRegionVolumeRequest(groupId, volumeName, vnfType, vnfId, tenantId, cloudRegion, namespace, modelCustomizationId)
259                 String payloadXml = utils.formatXml(payload)
260                 utils.logAudit(payloadXml)
261                 
262                 APIResponse response = aaiUtil.executeAAIPutCall(execution, createAAIVolumeGrpNameUrlRequest, payloadXml)
263                                 
264                 String returnCode = response.getStatusCode()
265                 String aaiResponseAsString = response.getResponseBodyAsString()
266                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
267                 
268                 utils.logAudit("AAI create volume group return code: " + returnCode)
269                 utils.logAudit("AAI create volume group response: " + aaiResponseAsString)
270
271                 execution.setVariable(prefix+"createAAIVolumeGrpNameReturnCode", returnCode)
272                 execution.setVariable(prefix+"createAAIVolumeGrpNameResponse", aaiResponseAsString)
273
274                 ExceptionUtil exceptionUtil = new ExceptionUtil()
275                 
276                 if (returnCode =='201') {
277                         execution.setVariable(prefix+"isAAIRollbackNeeded", true)
278                 } else {
279                         execution.setVariable(prefix+"isErrorMessageException", true)
280                         if (returnCode=='404') {
281                                 // @TODO: verify return code and make static LITERAL
282                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to create volume group in AAI. Response code: 404")
283                         } else {
284                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
285                                 utils.log("DEBUG", " AAI Adapter Query Failed.  WorkflowException - " + "\n" + aWorkflowException, isDebugEnabled)
286                                 throw new BpmnError("MSOWorkflowException")
287                         }
288                 }
289         }
290
291         /**
292          * Prepare VNF adapter create request XML
293          * @param execution
294          */
295         public void prepareVnfAdapterCreateRequest(Execution execution, isDebugEnabled) {
296                 
297                 
298                 def volumeRequest  = execution.getVariable(prefix+'Request')
299                 def requestId = execution.getVariable(prefix+'requestId')
300                 def serviceId = execution.getVariable(prefix+'serviceId')
301                 
302                 def aaiGenericVnfResponse = execution.getVariable(prefix+'AAIQueryGenericVfnResponse')
303                 def vnfId = utils.getNodeText1(aaiGenericVnfResponse, 'vnf-id')
304                 def vnfName = utils.getNodeText1(aaiGenericVnfResponse, 'vnf-name')
305                 def modelCustomizationId = getNodeTextForce(volumeRequest, "model-customization-id")
306                                 
307                 String messageId = UUID.randomUUID()
308                 utils.log("DEBUG", "messageId to be used is generated: " + messageId, isDebugEnabled)
309
310                 // prepare vnf request for vnfAdapterCreateV1
311                 def cloudSiteId = utils.getNodeText1(volumeRequest, 'aic-cloud-region')
312                 def tenantId = utils.getNodeText1(volumeRequest, "tenant-id")
313                 def vnfType = utils.getNodeText1(volumeRequest, "vnf-type")
314                 def vnfVersion = utils.getNodeText1(volumeRequest, "asdc-service-model-version")
315                 def vnfModuleType = utils.getNodeText1(volumeRequest, "vf-module-model-name")
316                 def volumeGroupnName = utils.getNodeText1(volumeRequest, "volume-group-name")
317
318                 def volumeParamsXml = utils.getNodeXml(volumeRequest, 'volume-params')
319                 def volumeGroupParams = transformVolumeParamsToEntries(volumeParamsXml)
320
321                 utils.log("DEBUG", "volumeGroupParams: "+ volumeGroupParams, isDebugEnabled)
322
323                 String volumeGroupId = execution.getVariable('volume-group-id')
324                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) 
325                 def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
326                 if ('true'.equals(useQualifiedHostName)) {
327                                 notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
328                 }
329                 utils.log("DEBUG", "CreateVfModuleVolume - notificationUrl: "+ notificationUrl, isDebugEnabled)
330                 
331                 def backoutOnFailure = execution.getVariable("DCVFMODVOLV1_rollbackEnabled")
332                 utils.log("DEBUG", "backoutOnFailure: "+ backoutOnFailure, isDebugEnabled)
333                 
334                 // build request
335                 String vnfSubCreateWorkflowRequest =
336                 """
337                         <createVolumeGroupRequest>
338                                 <cloudSiteId>${cloudSiteId}</cloudSiteId>
339                                 <tenantId>${tenantId}</tenantId>
340                                 <vnfId>${vnfId}</vnfId>
341                                 <vnfName>${vnfName}</vnfName>
342                                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
343                                 <volumeGroupName>${volumeGroupnName}</volumeGroupName>
344                                 <vnfType>${vnfType}</vnfType>
345                                 <vnfVersion>${vnfVersion}</vnfVersion>
346                                 <vfModuleType>${vnfModuleType}</vfModuleType>
347                                 <modelCustomizationUuid>${modelCustomizationId}</modelCustomizationUuid>
348                                 <volumeGroupParams>
349                                         <entry>
350                                                 <key>vnf_id</key>
351                                                 <value>${vnfId}</value>
352                                         </entry>
353                                         <entry>
354                                                 <key>vnf_name</key>
355                                                 <value>${vnfName}</value>
356                                         </entry>
357                                         <entry>
358                                                 <key>vf_module_id</key>
359                                                 <value>${volumeGroupId}</value>
360                                         </entry>
361                                         <entry>
362                                                 <key>vf_module_name</key>
363                                                 <value>${volumeGroupnName}</value>
364                                         </entry>
365                                         ${volumeGroupParams}
366                             </volumeGroupParams>
367                                 <skipAAI>true</skipAAI>
368                                 <backout>${backoutOnFailure}</backout>
369                                 <failIfExists>true</failIfExists>
370                             <msoRequest>
371                                 <requestId>${requestId}</requestId>
372                                 <serviceInstanceId>${serviceId}</serviceInstanceId>
373                             </msoRequest>
374                             <messageId>${messageId}</messageId>
375                             <notificationUrl>${notificationUrl}</notificationUrl>
376                         </createVolumeGroupRequest>
377                 """
378
379                 String vnfSubCreateWorkflowRequestAsString = utils.formatXml(vnfSubCreateWorkflowRequest)
380                 utils.logAudit(vnfSubCreateWorkflowRequestAsString)
381                 utils.log('DEBUG', vnfSubCreateWorkflowRequestAsString, isDebugEnabled)
382                 execution.setVariable(prefix+"createVnfARequest", vnfSubCreateWorkflowRequestAsString)
383                 
384                 // build rollback request for use later if needed
385                 
386                 String vnfSubRollbackWorkflowRequest =
387                 """<rollbackVolumeGroupRequest>
388                                 <cloudSiteId>${cloudSiteId}</cloudSiteId>
389                                 <tenantId>${tenantId}</tenantId>
390                                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
391                                 <skipAAI>true</skipAAI>
392                                 <volumeGroupCreated>true</volumeGroupCreated>
393                             <msoRequest>
394                                 <requestId>${requestId}</requestId>
395                                 <serviceInstanceId>${serviceId}</serviceInstanceId>
396                             </msoRequest>
397                             <messageId>${messageId}</messageId>
398                             <notificationUrl>${notificationUrl}</notificationUrl>
399                         </rollbackVolumeGroupRequest>"""
400
401                 utils.log("DEBUG", "Sub Vnf flow rollback request: vnfSubRollbackWorkflowRequest " + "\n" + vnfSubRollbackWorkflowRequest, isDebugEnabled)
402                 
403                 String vnfSubRollbackWorkflowRequestAsString = utils.formatXml(vnfSubRollbackWorkflowRequest)
404                 execution.setVariable(prefix+"rollbackVnfARequest", vnfSubRollbackWorkflowRequestAsString)
405         }
406
407         
408
409         /**
410          * Update voulume group in AAI 
411          * @TODO: Can we re-use the create method??
412          * @param execution
413          * @param isDebugEnabled
414          */
415         public void callRESTUpdateCreatedVolGrpName(Execution execution, isDebugEnabled) {
416                 
417                 // get variables
418                 String requeryAAIVolGrpNameResponse = execution.getVariable(prefix+"queryAAIVolGrpNameResponse")
419                 String volumeGroupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id")
420                 String modelCustomizationId = getNodeTextForce(requeryAAIVolGrpNameResponse, "vf-module-persona-model-customization-id")
421                 String cloudRegion = execution.getVariable(prefix+"aicCloudRegion")
422                 
423                 AaiUtil aaiUtil = new AaiUtil(this)
424                 String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution)
425                 String updateAAIVolumeGroupUrlRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, 'UTF-8')
426                 
427                 String namespace =  aaiUtil.getNamespaceFromUri(aaiUtil.getCloudInfrastructureCloudRegionUri(execution))
428
429                 utils.logAudit(updateAAIVolumeGroupUrlRequest)
430
431                 //Prepare payload (PUT)
432                 String createVnfAResponse = execution.getVariable(prefix+"createVnfAResponse")
433                 
434                 // @TODO: revisit
435                 // if VID request createVnfresponse will be null, use vnf from JSON request
436                 def vnfId = ""
437                 if(createVnfAResponse == null || createVnfAResponse == "") {
438                         vnfId = execution.getVariable(prefix+'vnfId')
439                 }
440                 else {
441                         vnfId = utils.getNodeText(createVnfAResponse, "volumeGroupStackId")
442                 }
443                 
444                 NetworkUtils networkUtils = new NetworkUtils()
445                 String payload = networkUtils.updateCloudRegionVolumeRequest(requeryAAIVolGrpNameResponse, vnfId, namespace, modelCustomizationId)
446                 String payloadXml = utils.formatXml(payload)
447                 
448                 //execution.setVariable(prefix+"updateCreatedAAIVolumeGrpNamePayloadRequest", payloadXml)
449                 utils.logAudit(payload)
450                 //utils.log("DEBUG", " 'payload' to Update Created VolumeGroupName - " + "\n" + payloadXml, isDebugEnabled)
451
452                 APIResponse response = aaiUtil.executeAAIPutCall(execution, updateAAIVolumeGroupUrlRequest, payloadXml)
453                 
454                 String returnCode = response.getStatusCode()
455                 String aaiResponseAsString = response.getResponseBodyAsString()
456                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
457                 
458                 utils.logAudit("AAI create volume group return code: " + returnCode)
459                 utils.logAudit("AAI create volume group response: " + aaiResponseAsString)
460
461                 ExceptionUtil exceptionUtil = new ExceptionUtil()
462
463                 if (returnCode =='200') {
464                         execution.setVariable(prefix+"updateCreatedAAIVolumeGrpNameResponse", aaiResponseAsString)
465                         execution.setVariable(prefix+"isPONR", true)
466                 } else {
467                         execution.setVariable(prefix+"isErrorMessageException", true)
468                         if (returnCode=='404') {
469                                 // @TODO: verify return code and make static LITERAL
470                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to update volume group in AAI. Response code: 404")
471                         } else {
472                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
473                                 utils.log("DEBUG", " AAI Adapter Query Failed.  WorkflowException - " + "\n" + aWorkflowException, isDebugEnabled)
474                                 throw new BpmnError("MSOWorkflowException")
475                         }
476                 }
477         }
478
479         
480         /**
481          * Query AAI service instance
482          * @param execution
483          * @param isDebugEnabled
484          */
485         public void callRESTQueryAAIGenericVnf(Execution execution, isDebugEnabled) {
486                 
487                 def request = execution.getVariable(prefix+"Request")
488                 def vnfId = execution.getVariable('vnf-id')
489                 
490                 AaiUtil aaiUtil = new AaiUtil(this)
491                 String aaiEndpoint = aaiUtil.getNetworkGenericVnfEndpoint(execution)
492                 def String queryAAIRequest = aaiEndpoint + "/" + UriUtils.encode(vnfId, "UTF-8")
493                 
494                 utils.logAudit("AAI query generic vnf request: " + queryAAIRequest)
495                 
496                 APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest)
497                 
498                 String returnCode = response.getStatusCode()
499                 String aaiResponseAsString = response.getResponseBodyAsString()
500                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
501                 
502                 utils.logAudit("AAI query generic vnf return code: " + returnCode)
503                 utils.logAudit("AAI query generic vnf response: " + aaiResponseAsString)
504
505                 //utils.log("DEBUG", "AAI query generic vnf return code: " + returnCode, isDebugEnabled)
506                 //utils.log("DEBUG", "AAI query generic vnf response: " + aaiResponseAsString, isDebugEnabled)
507                 
508                 ExceptionUtil exceptionUtil = new ExceptionUtil()
509                 
510                 if (returnCode=='200') {
511                         utils.log("DEBUG", 'Generic vnf ' + vnfId + ' found in AAI.', isDebugEnabled)
512                         execution.setVariable(prefix+'AAIQueryGenericVfnResponse', aaiResponseAsString)
513                 } else {
514                         if (returnCode=='404') {
515                                 def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.'
516                                 utils.log("DEBUG", message, isDebugEnabled)
517                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message)
518                         } else {
519                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
520                                 throw new BpmnError("MSOWorkflowException")
521                         }
522                 }
523         }
524
525         public void callRESTDeleteAAIVolumeGroup(Execution execution, isDebugEnabled) {
526
527                 callRESTQueryAAIVolGrpName(execution, isDebugEnabled)
528                 
529                 def queryAaiVolumeGroupResponse = execution.getVariable(prefix+'queryAAIVolGrpNameResponse')
530                 
531                 def volumeGroupId = utils.getNodeText(queryAaiVolumeGroupResponse, "volume-group-id")
532                 def resourceVersion = utils.getNodeText(queryAaiVolumeGroupResponse, "resource-version")
533
534                 def cloudRegion = execution.getVariable(prefix+"aicCloudRegion")
535                 
536                 AaiUtil aaiUtil = new AaiUtil(this)
537                 String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution)
538                 String deleteAAIVolumeGrpIdRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups/volume-group" + '/' +  volumeGroupId + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8")
539
540                 utils.logAudit('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest)
541                 
542                 APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest)
543                 
544                 String returnCode = response.getStatusCode()
545                 String aaiResponseAsString = response.getResponseBodyAsString()
546                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
547                 
548                 utils.logAudit("AAI delete volume group return code: " + returnCode)
549                 utils.logAudit("AAI delete volume group response: " + aaiResponseAsString)
550
551                 ExceptionUtil exceptionUtil = new ExceptionUtil()
552
553                 def volumeGroupNameFound = prefix+'volumeGroupNameFound'
554                 if (returnCode=='200' || returnCode=='204' ) {
555                         utils.log("DEBUG", "Volume group $volumeGroupId deleted.", isDebugEnabled)
556                 } else {
557                         if (returnCode=='404') {
558                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404")
559                         } else {
560                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
561                                 throw new BpmnError("MSOWorkflowException")
562                         }
563                 }
564         }
565
566         
567         
568         
569         
570         public void prepareSuccessDBRequest(Execution execution, isDebugEnabled) {
571                 String requestId = execution.getVariable(prefix+'requestId')
572                 String dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs')
573                 prepareDBRequest(execution, requestId, "VolumeGroup successfully created.", "COMPLETED", "100", dbVnfOutputs, isDebugEnabled)
574         }
575         
576         public void prepareFailDbRequest(Execution execution, isDebugEnabled) {
577                 
578                 WorkflowException we = execution.getVariable("WorkflowException")
579                 
580                 String requestId = execution.getVariable(prefix+'requestId')
581                 String dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs')
582                 prepareDBRequest(execution, requestId, we.getErrorMessage(), "FAILURE", "", dbVnfOutputs, isDebugEnabled)
583
584         }
585         
586         
587         /**
588          * Prepare Infra DB XML Request 
589          * @param execution
590          */
591         public void prepareDBRequest (Execution execution, String requestId, String statusMessage, String requestStatus, String progress, String dbVnfOutputs, isDebugEnabled) {
592                 
593                 String dbRequest =
594                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
595                         <soapenv:Header/>
596                         <soapenv:Body>
597                                 <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
598                                         <requestId>${requestId}</requestId>
599                                         <lastModifiedBy>BPMN</lastModifiedBy>
600                                         <statusMessage>${statusMessage}</statusMessage>
601                                         <responseBody></responseBody>
602                                         <requestStatus>${requestStatus}</requestStatus>
603                                         <progress>${progress}</progress>
604                                         <vnfOutputs>${dbVnfOutputs}</vnfOutputs>
605                                 </ns:updateInfraRequest>
606                         </soapenv:Body>
607                    </soapenv:Envelope>"""
608
609            utils.log("DEBUG", " DB Adapter Request - " + "\n" + dbRequest, isDebugEnabled)
610            String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
611            
612            execution.setVariable(prefix+"createDBRequest", buildDeleteDBRequestAsString)
613            
614            utils.logAudit(buildDeleteDBRequestAsString)
615          }
616
617
618
619         
620         public void postProcessResponse (Execution execution, isDebugEnabled) {
621
622                 String dbReturnCode = execution.getVariable(prefix+"dbReturnCode")
623                 utils.log("DEBUG", "DB Update Response Code  : " + dbReturnCode, isDebugEnabled)
624                 
625                 String createDBResponse =  execution.getVariable(prefix+"createDBResponse")
626                 utils.logAudit(createDBResponse)
627
628                 String source = execution.getVariable(prefix+"source")
629                 String requestId = execution.getVariable(prefix+'requestId')
630
631                 String msoCompletionRequest =
632                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
633                                                         xmlns:ns="http://org.openecomp/mso/request/types/v1">
634                                         <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
635                                                 <request-id>${requestId}</request-id>
636                                                 <action>CREATE</action>
637                                                 <source>${source}</source>
638                                         </request-info>
639                                         <aetgt:mso-bpel-name>BPEL Volume Group action: CREATE</aetgt:mso-bpel-name>
640                                 </aetgt:MsoCompletionRequest>"""
641
642                 // Format Response
643                 String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
644                 utils.logAudit(xmlMsoCompletionRequest)
645                 
646                 // normal path
647                 if (dbReturnCode == "200") {
648                                 execution.setVariable(prefix+"Success", true)
649                                 execution.setVariable(prefix+"CompleteMsoProcessRequest", xmlMsoCompletionRequest)
650                                 utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
651                 } else {
652                                 execution.setVariable(prefix+"isErrorMessageException", true)
653                                 utils.log("DEBUG", " DB Update failed, code: " + dbReturnCode + ", going to Unexpected Error.", isDebugEnabled)
654                 }
655         }
656
657 }