aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy
blob: db90cd0d7be5f9bf6528b8f1aa107002460a3bea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Modifications Copyright (c) 2019 Samsung
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.so.bpmn.infrastructure.scripts

import org.apache.commons.lang3.StringUtils
import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.delegate.DelegateExecution
import org.onap.aai.domain.yang.Relationship
import org.onap.aai.domain.yang.RelationshipData
import org.onap.aai.domain.yang.VolumeGroup
import org.onap.so.bpmn.common.scripts.AaiUtil
import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
import org.onap.so.bpmn.common.scripts.ExceptionUtil
import org.onap.so.bpmn.common.scripts.MsoUtils
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.bpmn.core.WorkflowException
import org.onap.so.bpmn.core.json.JsonUtils
import org.onap.aaiclient.client.aai.AAIObjectType
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
import org.onap.aaiclient.client.aai.entities.Relationships
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
import org.onap.so.constants.Defaults
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import javax.ws.rs.NotFoundException

class DoDeleteVfModuleVolumeV2 extends AbstractServiceTaskProcessor{
    private static final Logger logger = LoggerFactory.getLogger( DoDeleteVfModuleVolumeV2.class);

	String prefix="DDVMV_"
	ExceptionUtil exceptionUtil = new ExceptionUtil()
	XmlParser xmlParser = new XmlParser()
	JsonUtils jsonUtil = new JsonUtils()

	@Override
	public void preProcessRequest(DelegateExecution execution) {
		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
		preProcessRequest(execution, isDebugEnabled)
	}

	/**
	 * Set default variable values
	 * @param execution
	 * @param isDebugLogEnabled
	 */
	public void preProcessRequest (DelegateExecution execution, isDebugEnabled) {

		//Input:
		//  msoRequestId
		//  isDebugLogEnabled
		//  failIfNotFound (Optional)
		//  serviceInstanceId (Optional)
		//  vnfId (Optional)
		//  volumeGroupId
		//  vfModuleModelInfo (Optional)
		//  lcpCloudRegionId (Optional)			@TODO: this is actually required
		//  tenantId (Optional)					@TODO: this is actually required
		//  cloudConfiguration					@TODO: temporary solution? this contains lcpCloudregion and tenantId
		//
		//Output:
		//  workflowException					@TODO: actual variable name is WorkflowException
		//  rolledBack
		//  wasDeleted

		execution.setVariable('prefix', prefix)
		execution.setVariable('wasDeleted', 'false')

		def tenantId = execution.getVariable("tenantId")
		def cloudSiteId = execution.getVariable("lcpCloudRegionId")

		// if tenantId or lcpCloudregionId is not passed, get it from cloudRegionConfiguration variable
		if(!tenantId || !cloudSiteId) {
			def cloudConfiguration = execution.getVariable("cloudConfiguration")
			logger.debug("Using cloudConfiguration variable to get tenantId and lcpCloudRegionId - " + cloudConfiguration)
			tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId")
			execution.setVariable("tenantId", tenantId)
			cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId")
			execution.setVariable("lcpCloudRegionId", cloudSiteId)
			cloudOwner = jsonUtil.getJsonValue(cloudConfiguration, "cloudOwner")
			execution.setVariable("cloudOwner", cloudOwner)
		}
	}


	/**
	 * Set out 'wasDeleted' variable to 'true'
	 * @param execution
	 * @param isDebugLogEnabled
	 */
	public void postProcess(DelegateExecution execution, isDebugLogEnabled) {
		execution.setVariable('wasDeleted', 'true')
	}


	/**
	 * Query and set cloud region to use for AAI calls
	 * Output variables: prefix+'aicCloudRegion', prefix+'cloudRegion'
	 * @param execution
	 * @param isDebugEnabled
	 */
	public void callRESTQueryAAICloudRegion(DelegateExecution execution, isDebugEnabled) {

		String cloudRegion = execution.getVariable('lcpCloudRegionId')
		AaiUtil aaiUtil = new AaiUtil(this)

		AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, Defaults.CLOUD_OWNER.toString(), cloudRegion)
		def queryCloudRegionRequest = aaiUtil.createAaiUri(uri)

		cloudRegion = aaiUtil.getAAICloudReqion(execution,  queryCloudRegionRequest, "PO", cloudRegion)

		if ((cloudRegion != "ERROR")) {
			if(execution.getVariable(prefix+"queryCloudRegionReturnCode") == "404") {
				execution.setVariable(prefix+"aicCloudRegion", "AAIAIC25")
			}
			else{
				execution.setVariable(prefix+"aicCloudRegion", cloudRegion)
			}
		}
		else {
			logger.debug("AAI Query Cloud Region Unsuccessful.")
			exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable(prefix+"queryCloudRegionReturnCode"))
		}
	}


	/**
	 * Query AAI Volume Group
	 * Output variables: prefix+'queryAAIVolGrpResponse'; prefix+'volumeGroupHeatStackId'
	 * @param execution
	 * @param isDebugLogEnabled
	 */
	public void callRESTQueryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) {

		def tenantId = execution.getVariable('tenantId')
		def volumeGroupId = execution.getVariable('volumeGroupId')
		if(volumeGroupId == null) {
			exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'volumeGroupId is not provided in the request')
			throw new Exception('volume-group-id is not provided in the request')
		}
		String cloudRegion = execution.getVariable(prefix+'aicCloudRegion')

		try {
			AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP , Defaults.CLOUD_OWNER.toString(), cloudRegion,volumeGroupId)
			Optional<VolumeGroup> volumeGroupOps = getAAIClient().get(VolumeGroup.class,resourceUri)
            if(volumeGroupOps.present) {
                VolumeGroup volumeGroup = volumeGroupOps.get()
                execution.setVariable(prefix + "queryAAIVolGrpResponse", volumeGroup)
                def heatStackId = volumeGroup.getHeatStackId()==null ? '' : volumeGroup.getHeatStackId()
                execution.setVariable(prefix+'volumeGroupHeatStackId', heatStackId)

                logger.debug('Heat stack id from AAI response: ' + heatStackId)
				AAIResultWrapper wrapper = getAAIClient().get(resourceUri);
				Optional<Relationships> relationships = wrapper.getRelationships()
				String volumeGroupTenantId = null

				if(relationships.isPresent()){
					if(relationships.get().getRelatedAAIUris(AAIObjectType.VF_MODULE)){
						logger.debug('Volume Group ' + volumeGroupId + ' currently in use')
						exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.")
					}
					for(AAIResourceUri aaiResourceUri: relationships.get().getRelatedAAIUris(AAIObjectType.TENANT)){
						volumeGroupTenantId = aaiResourceUri.getURIKeys().get("tenant-id")
					}
				}

                logger.debug('Tenant ID from AAI response: ' + volumeGroupTenantId)

                if (volumeGroupTenantId == null) {
                    logger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}")
                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}")
                }

                if (volumeGroupTenantId != tenantId) {
                    def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId +	' retrieved from AAI for Volume Group Id ' + volumeGroupId
                    logger.debug("Error in DeleteVfModuleVolume: " + errorMessage)
                    exceptionUtil.buildAndThrowWorkflowException(execution, 5000, errorMessage)
                }
                logger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId )
            }else{
                execution.setVariable(prefix + "queryAAIVolGrpResponse", "Volume Group ${volumeGroupId} not found in AAI. Response code: 404")
                logger.debug("Volume Group ${volumeGroupId} not found in AAI")
                exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404")
            }
		}catch (Exception ex) {
            execution.setVariable(prefix+"queryAAIVolGrpResponse", ex.getMessage())
            WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(ex.getMessage(), execution)
            throw new BpmnError("MSOWorkflowException")
		}
	}

	/**
	 * Format VNF Adapter subflow request XML
	 * Variables: prefix+'deleteVnfARequest'
	 * @param execution
	 * @param isDebugLogEnabled
	 */
	public void prepareVnfAdapterDeleteRequest(DelegateExecution execution, isDebugLogEnabled) {
		def cloudRegion = execution.getVariable(prefix+'aicCloudRegion')
		def cloudOwner = execution.getVariable(prefix+'cloudOwner')
		def tenantId = execution.getVariable('tenantId')										// input parameter (optional) - see preProcessRequest
		def volumeGroupId = execution.getVariable('volumeGroupId')								// input parameter (required)
		def volumeGroupHeatStackId = execution.getVariable(prefix+'volumeGroupHeatStackId')		// from AAI query volume group
		def requestId = execution.getVariable('msoRequestId')									// input parameter (required)
		def serviceId = execution.getVariable('serviceInstanceId')								// imput parameter (optional)

		def messageId = UUID.randomUUID().toString()
		def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
		def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
		if ('true'.equals(useQualifiedHostName)) {
				notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
		}

		String vnfAdapterRestRequest = """
			<deleteVolumeGroupRequest>
				<cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
				<cloudOwner>${MsoUtils.xmlEscape(cloudOwner)}</cloudOwner>
				<tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
				<volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId>
				<volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupHeatStackId)}</volumeGroupStackId>
				<skipAAI>true</skipAAI>
			    <msoRequest>
			        <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
			        <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId>
			    </msoRequest>
			    <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
			    <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
			</deleteVolumeGroupRequest>
		"""
		vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest)
		execution.setVariable(prefix+'deleteVnfARequest', vnfAdapterRestRequest)
		logger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest)
	}


	/**
	 * Delete volume group in AAI
	 * @param execution
	 * @param isDebugEnabled
	 */
	public void callRESTDeleteAAIVolumeGroup(DelegateExecution execution, isDebugEnabled) {

		// get variables
		VolumeGroup volumeGroupResponse = execution.getVariable(prefix+"queryAAIVolGrpResponse")
		String volumeGroupId = volumeGroupResponse.getVolumeGroupId()
		String cloudRegion = execution.getVariable(prefix+'aicCloudRegion')

        try {
            AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId)
            getAAIClient().delete(resourceUri)
            logger.debug("Volume group $volumeGroupId deleted.")
        }catch (NotFoundException ex) {
            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404")
        }catch (Exception ex) {
            WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(ex.getMessage(), execution)
            throw new BpmnError("MSOWorkflowException")
        }
	}

}