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