Springboot 2.0 upgrade
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteVfModuleVolumeV2.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.apache.commons.lang3.StringUtils
24 import org.camunda.bpm.engine.delegate.BpmnError
25 import org.camunda.bpm.engine.delegate.DelegateExecution
26 import org.onap.aai.domain.yang.Relationship
27 import org.onap.aai.domain.yang.RelationshipData
28 import org.onap.aai.domain.yang.VolumeGroup
29 import org.onap.so.bpmn.common.scripts.AaiUtil
30 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
31 import org.onap.so.bpmn.common.scripts.ExceptionUtil
32 import org.onap.so.bpmn.common.scripts.MsoUtils
33 import org.onap.so.bpmn.core.UrnPropertiesReader;
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.bpmn.core.json.JsonUtils
36 import org.onap.so.client.aai.AAIObjectType
37 import org.onap.so.client.aai.entities.AAIResultWrapper
38 import org.onap.so.client.aai.entities.Relationships
39 import org.onap.so.client.aai.entities.uri.AAIResourceUri
40 import org.onap.so.client.aai.entities.uri.AAIUriFactory
41 import org.onap.so.constants.Defaults
42 import org.onap.so.logger.MsoLogger
43 import javax.ws.rs.NotFoundException
44
45 class DoDeleteVfModuleVolumeV2 extends AbstractServiceTaskProcessor{
46         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModuleVolumeV2.class);
47
48         String prefix="DDVMV_"
49         ExceptionUtil exceptionUtil = new ExceptionUtil()
50         XmlParser xmlParser = new XmlParser()
51         JsonUtils jsonUtil = new JsonUtils()
52
53         @Override
54         public void preProcessRequest(DelegateExecution execution) {
55                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
56                 preProcessRequest(execution, isDebugEnabled)
57         }
58
59         /**
60          * Set default variable values
61          * @param execution
62          * @param isDebugLogEnabled
63          */
64         public void preProcessRequest (DelegateExecution execution, isDebugEnabled) {
65
66                 //Input:
67                 //  msoRequestId
68                 //  isDebugLogEnabled
69                 //  failIfNotFound (Optional)
70                 //  serviceInstanceId (Optional)
71                 //  vnfId (Optional)
72                 //  volumeGroupId
73                 //  vfModuleModelInfo (Optional)
74                 //  lcpCloudRegionId (Optional)                 @TODO: this is actually required
75                 //  tenantId (Optional)                                 @TODO: this is actually required
76                 //  cloudConfiguration                                  @TODO: temporary solution? this contains lcpCloudregion and tenantId
77                 //
78                 //Output:
79                 //  workflowException                                   @TODO: actual variable name is WorkflowException
80                 //  rolledBack
81                 //  wasDeleted
82
83                 execution.setVariable('prefix', prefix)
84                 execution.setVariable('wasDeleted', 'false')
85
86                 def tenantId = execution.getVariable("tenantId")
87                 def cloudSiteId = execution.getVariable("lcpCloudRegionId")
88
89                 // if tenantId or lcpCloudregionId is not passed, get it from cloudRegionConfiguration variable
90                 if(!tenantId || !cloudSiteId) {
91                         def cloudConfiguration = execution.getVariable("cloudConfiguration")
92                         msoLogger.debug("Using cloudConfiguration variable to get tenantId and lcpCloudRegionId - " + cloudConfiguration)
93                         tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId")
94                         execution.setVariable("tenantId", tenantId)
95                         cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId")
96                         execution.setVariable("lcpCloudRegionId", cloudSiteId)
97                         cloudOwner = jsonUtil.getJsonValue(cloudConfiguration, "cloudOwner")
98                         execution.setVariable("cloudOwner", cloudOwner)
99                 }
100         }
101
102
103         /**
104          * Set out 'wasDeleted' variable to 'true'
105          * @param execution
106          * @param isDebugLogEnabled
107          */
108         public void postProcess(DelegateExecution execution, isDebugLogEnabled) {
109                 execution.setVariable('wasDeleted', 'true')
110         }
111
112
113         /**
114          * Query and set cloud region to use for AAI calls
115          * Output variables: prefix+'aicCloudRegion', prefix+'cloudRegion'
116          * @param execution
117          * @param isDebugEnabled
118          */
119         public void callRESTQueryAAICloudRegion(DelegateExecution execution, isDebugEnabled) {
120
121                 String cloudRegion = execution.getVariable('lcpCloudRegionId')
122                 AaiUtil aaiUtil = new AaiUtil(this)
123
124                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, Defaults.CLOUD_OWNER.toString(), cloudRegion)
125                 def queryCloudRegionRequest = aaiUtil.createAaiUri(uri)
126
127                 cloudRegion = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "PO", cloudRegion)
128
129                 if ((cloudRegion != "ERROR")) {
130                         if(execution.getVariable(prefix+"queryCloudRegionReturnCode") == "404") {
131                                 execution.setVariable(prefix+"aicCloudRegion", "AAIAIC25")
132                         }
133                         else{
134                                 execution.setVariable(prefix+"aicCloudRegion", cloudRegion)
135                         }
136                 }
137                 else {
138                         msoLogger.debug("AAI Query Cloud Region Unsuccessful.")
139                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable(prefix+"queryCloudRegionReturnCode"))
140                 }
141         }
142
143
144         /**
145          * Query AAI Volume Group
146          * Output variables: prefix+'queryAAIVolGrpResponse'; prefix+'volumeGroupHeatStackId'
147          * @param execution
148          * @param isDebugLogEnabled
149          */
150         public void callRESTQueryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) {
151
152                 def tenantId = execution.getVariable('tenantId')
153                 def volumeGroupId = execution.getVariable('volumeGroupId')
154                 if(volumeGroupId == null) {
155                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'volumeGroupId is not provided in the request')
156                         throw new Exception('volume-group-id is not provided in the request')
157                 }
158                 String cloudRegion = execution.getVariable(prefix+'aicCloudRegion')
159
160                 try {
161                         AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP , Defaults.CLOUD_OWNER.toString(), cloudRegion,volumeGroupId)
162                         Optional<VolumeGroup> volumeGroupOps = getAAIClient().get(VolumeGroup.class,resourceUri)
163             if(volumeGroupOps.present) {
164                 VolumeGroup volumeGroup = volumeGroupOps.get()
165                 execution.setVariable(prefix + "queryAAIVolGrpResponse", volumeGroup)
166                 def heatStackId = volumeGroup.getHeatStackId()==null ? '' : volumeGroup.getHeatStackId()
167                 execution.setVariable(prefix+'volumeGroupHeatStackId', heatStackId)
168
169                 msoLogger.debug('Heat stack id from AAI response: ' + heatStackId)
170                                 AAIResultWrapper wrapper = getAAIClient().get(uri);
171                                 Optional<Relationships> relationships = wrapper.getRelationships()
172                                 String volumeGroupTenantId = null
173
174                                 if(relationships.isPresent()){
175                                         if(relationships.get().getRelatedAAIUris(AAIObjectType.VF_MODULE)){
176                                                 msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use')
177                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.")
178                                         }
179                                         for(AAIResourceUri aaiResourceUri: relationships.get().getRelatedAAIUris(AAIObjectType.TENANT)){
180                                                 volumeGroupTenantId = aaiResourceUri.getURIKeys().get("tenant-id")
181                                         }
182                                 }
183
184                 msoLogger.debug('Tenant ID from AAI response: ' + volumeGroupTenantId)
185
186                 if (volumeGroupTenantId == null) {
187                     msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}")
188                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}")
189                 }
190
191                 if (volumeGroupTenantId != tenantId) {
192                     def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + ' retrieved from AAI for Volume Group Id ' + volumeGroupId
193                     msoLogger.debug("Error in DeleteVfModuleVolume: " + errorMessage)
194                     exceptionUtil.buildAndThrowWorkflowException(execution, 5000, errorMessage)
195                 }
196                 msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId )
197             }else{
198                 execution.setVariable(prefix + "queryAAIVolGrpResponse", "Volume Group ${volumeGroupId} not found in AAI. Response code: 404")
199                 msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI")
200                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404")
201             }
202                 }catch (Exception ex) {
203             execution.setVariable(prefix+"queryAAIVolGrpResponse", ex.getMessage())
204             WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(ex.getMessage(), execution)
205             throw new BpmnError("MSOWorkflowException")
206                 }
207         }
208
209         /**
210          * Format VNF Adapter subflow request XML
211          * Variables: prefix+'deleteVnfARequest'
212          * @param execution
213          * @param isDebugLogEnabled
214          */
215         public void prepareVnfAdapterDeleteRequest(DelegateExecution execution, isDebugLogEnabled) {
216                 def cloudRegion = execution.getVariable(prefix+'aicCloudRegion')
217                 def tenantId = execution.getVariable('tenantId')                                                                                // input parameter (optional) - see preProcessRequest
218                 def volumeGroupId = execution.getVariable('volumeGroupId')                                                              // input parameter (required)
219                 def volumeGroupHeatStackId = execution.getVariable(prefix+'volumeGroupHeatStackId')             // from AAI query volume group
220                 def requestId = execution.getVariable('msoRequestId')                                                                   // input parameter (required)
221                 def serviceId = execution.getVariable('serviceInstanceId')                                                              // imput parameter (optional)
222
223                 def messageId = UUID.randomUUID().toString()
224                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
225                 def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
226                 if ('true'.equals(useQualifiedHostName)) {
227                                 notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
228                 }
229
230                 String vnfAdapterRestRequest = """
231                         <deleteVolumeGroupRequest>
232                                 <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
233                                 <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
234                                 <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId>
235                                 <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupHeatStackId)}</volumeGroupStackId>
236                                 <skipAAI>true</skipAAI>
237                             <msoRequest>
238                                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
239                                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId>
240                             </msoRequest>
241                             <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
242                             <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
243                         </deleteVolumeGroupRequest>
244                 """
245                 vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest)
246                 execution.setVariable(prefix+'deleteVnfARequest', vnfAdapterRestRequest)
247                 msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest)
248         }
249
250
251         /**
252          * Delete volume group in AAI
253          * @param execution
254          * @param isDebugEnabled
255          */
256         public void callRESTDeleteAAIVolumeGroup(DelegateExecution execution, isDebugEnabled) {
257
258                 // get variables
259                 VolumeGroup volumeGroupResponse = execution.getVariable(prefix+"queryAAIVolGrpResponse")
260                 String volumeGroupId = volumeGroupResponse.getVolumeGroupId()
261                 String cloudRegion = execution.getVariable(prefix+'aicCloudRegion')
262
263         try {
264             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId)
265             getAAIClient().delete(resourceUri)
266             msoLogger.debug("Volume group $volumeGroupId deleted.")
267         }catch (NotFoundException ex) {
268             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404")
269         }catch (Exception ex) {
270             WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(ex.getMessage(), execution)
271             throw new BpmnError("MSOWorkflowException")
272         }
273         }
274
275 }