aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy
blob: e64fda63567bc003cf0338e1f4d827a985bb5c36 (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*-
 * ============LICENSE_START=======================================================
 * OPENECOMP - MSO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.openecomp.mso.bpmn.common.scripts

import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.runtime.Execution
import org.openecomp.mso.bpmn.core.WorkflowException
import org.openecomp.mso.rest.APIResponse
import org.openecomp.mso.rest.RESTClient
import org.openecomp.mso.rest.RESTConfig
import org.springframework.web.util.UriUtils

public class PrepareUpdateAAIVfModule extends VfModuleBase {
	
	/**
	 * Initialize the flow's variables.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void initProcessVariables(Execution execution) {
		execution.setVariable('prefix', 'PUAAIVfMod_')
		execution.setVariable('PUAAIVfMod_vnfId', null)
		execution.setVariable('PUAAIVfMod_vfModuleId', null)
		execution.setVariable('PUAAIVfMod_vnfName', null)
		execution.setVariable('PUAAIVfMod_orchestrationStatus', null)
		execution.setVariable('PUAAIVfMod_vfModule', null)
		execution.setVariable('PUAAIVfMod_vfModuleOK', false)
		execution.setVariable('PUAAIVfMod_vfModuleValidationError', null)
		execution.setVariable('PUAAIVfMod_getVnfResponseCode' ,null)
		execution.setVariable('PUAAIVfMod_getVnfResponse', '')
		execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', null)
		execution.setVariable('PUAAIVfMod_updateVfModuleResponse', '')
		execution.setVariable('PUAAIVfMod_outVfModule', null)
	}	
	
	/**
	 * Check for missing elements in the received request.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void preProcessRequest(Execution execution) {
		def method = getClass().getSimpleName() + '.preProcessRequest(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)

		try {
			def xml = execution.getVariable('PrepareUpdateAAIVfModuleRequest')
			logDebug('Received request xml:\n' + xml, isDebugLogEnabled)
			utils.logAudit("PrepareUpdateAAIVfModule Request  : " + xml)
			
			initProcessVariables(execution)
			
			def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
			execution.setVariable('PUAAIVfMod_vnfId', vnfId)

			def vfModuleId = getRequiredNodeText(execution, xml,'vf-module-id')
			execution.setVariable('PUAAIVfMod_vfModuleId', vfModuleId)
			
			def orchestrationStatus = getRequiredNodeText(execution, xml,'orchestration-status')
			execution.setVariable('PUAAIVfMod_orchestrationStatus', orchestrationStatus)

			logDebug('Exited ' + method, isDebugLogEnabled)
		} catch (BpmnError e) {
			throw e;
		} catch (Exception e) {
			logError('Caught exception in ' + method, e)
			createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
		}
	}
	
	/**
	 * Using the received vnfId, query AAI to get the corresponding Generic VNF.
	 * A 200 response is expected with the Generic VNF in the response body.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void getGenericVnf(Execution execution) {
		def method = getClass().getSimpleName() + '.getGenericVnf(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)

		try {
			def vnfId = execution.getVariable('PUAAIVfMod_vnfId')
			
			AaiUtil aaiUriUtil = new AaiUtil(this)
			def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
			logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
			
			String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
				
			utils.logAudit("PrepareUpdateAAIVfModule: AAI endPoint  : " + endPoint)
			String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
			try {
				RESTConfig config = new RESTConfig(endPoint);
				def responseData = ''
				def aaiRequestId = UUID.randomUUID().toString()
				RESTClient client = new RESTClient(config).
					addHeader('X-TransactionId', aaiRequestId).
					addHeader('X-FromAppId', 'MSO').
					addHeader('Content-Type', 'application/xml').
					addHeader('Accept','application/xml');
				if (basicAuthCred != null && !"".equals(basicAuthCred)) {
					client.addAuthorizationHeader(basicAuthCred)
				}
				logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled)
				APIResponse response = client.httpGet()
				utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpGet to AAI")
				
				responseData = response.getResponseBodyAsString()
				execution.setVariable('PUAAIVfMod_getVnfResponseCode', response.getStatusCode())
				execution.setVariable('PUAAIVfMod_getVnfResponse', responseData)
				
				utils.logAudit("PrepareUpdateAAIVfModule: AAI Response : " + responseData)
				utils.logAudit("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode())
				
				logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
				logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
			} catch (Exception ex) {
				ex.printStackTrace()
				logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(), isDebugLogEnabled)
				execution.setVariable('PUAAIVfMod_getVnfResponseCode', 500)
				execution.setVariable('PUAAIVfMod_getVnfResponse', 'AAI GET Failed:' + ex.getMessage())
			}
			logDebug('Exited ' + method, isDebugLogEnabled)
		} catch (BpmnError e) {
			throw e;
		} catch (Exception e) {
			logError('Caught exception in ' + method, e)
			createWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage())
		}
	}
	
	/**
	 * Validate the VF Module.  That is, confirm that a VF Module with the input VF Module ID
	 * exists in the retrieved Generic VNF.  Then, check to make sure that if that VF Module
	 * is the base VF Module and it's not the only VF Module for this Generic VNF, that we're not
	 * attempting to delete it.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void validateVfModule(Execution execution) {
		def method = getClass().getSimpleName() + '.validateVfModule(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)
		
		try {
			def genericVnf = execution.getVariable('PUAAIVfMod_getVnfResponse')
			def vnfId = execution.getVariable('PUAAIVfMod_vnfId')
			def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId')
			def vnfName = getNodeTextForce(genericVnf, 'vnf-name')
			execution.setVariable('PUAAIVfMod_vnfName', vnfName)
			def VfModule vfModule = findVfModule(genericVnf, vfModuleId)
			if (vfModule == null) {
				def String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\''
				execution.setVariable('PUAAIVfMod_vfModuleValidationError', msg)
				execution.setVariable('PUAAIVfMod_vfModuleOK', false)
			} else {
				def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus')
				if (isDebugLogEnabled) {
					logDebug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() +
						', isOnlyVfModule=' + vfModule.isOnlyVfModule() + ', new orchestration-status=' + orchestrationStatus,
						isDebugLogEnabled)
				}
				if (vfModule.isBaseVfModule() && !vfModule.isOnlyVfModule() && orchestrationStatus.equals('pending-delete')) {
					def String msg = 'Orchestration status for VF Module \'' + vfModuleId +
						'\' cannot be set to \'pending-delete\' since it is the base VF Module and it\'s not the only VF Module in Generic VNF \'' + vnfId + '\''
					execution.setVariable('PUAAIVfMod_vfModuleValidationError', msg)
					execution.setVariable('PUAAIVfMod_vfModuleOK', false)
				} else {
					execution.setVariable('PUAAIVfMod_vfModule', vfModule)
					execution.setVariable('PUAAIVfMod_vfModuleOK', true)
				}
			}
			
			logDebug('Exited ' + method, isDebugLogEnabled)
		} catch (BpmnError e) {
			throw e;
		} catch (Exception e) {
			logError('Caught exception in ' + method, e)
			createWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage())
		}
	}
	
	/**
	 * Construct and send a PUT request to AAI to update the VF Module.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void updateVfModule(Execution execution) {
		def method = getClass().getSimpleName() + '.updateVfModule(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)
		
		try {
			// Construct payload
			def VfModule vfModule = (VfModule) execution.getVariable('PUAAIVfMod_vfModule')
			def Node newVfModuleNode = vfModule.getNode().clone()
			def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus')
			def Node orchestrationStatusNode = utils.getChildNode(newVfModuleNode, 'orchestration-status')
			if (orchestrationStatusNode == null) {
				// Node doesn't exist, this should never happen, right?
				new Node(newVfModuleNode, 'orchestration-status', orchestrationStatus)
			} else {
				// Node already exists, just give it a new value
				orchestrationStatusNode.setValue(orchestrationStatus)
			}
			def VfModule newVfModule = new VfModule(newVfModuleNode, vfModule.isOnlyVfModule())
			def payload = utils.nodeToString(newVfModuleNode)
			
			utils.logAudit("VfModule payload : " + payload)
			
			// Construct endpoint
			def vnfId = execution.getVariable('PUAAIVfMod_vnfId')
			def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId')
			
			
			AaiUtil aaiUriUtil = new AaiUtil(this)
			def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
			logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
			
			String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "/vf-modules/vf-module/" + UriUtils.encode(vfModuleId, "UTF-8")
			utils.logAudit("PrepareUpdateAAIVfModule: AAI endPoint  : " + endPoint)
			String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
			try {
				RESTConfig config = new RESTConfig(endPoint);
				def responseData = ''
				def aaiRequestId = UUID.randomUUID().toString()
				RESTClient client = new RESTClient(config).
					addHeader('X-TransactionId', aaiRequestId).
					addHeader('X-FromAppId', 'MSO').
					addHeader('Content-Type', 'application/xml').
					addHeader('Accept','application/xml');
				if (basicAuthCred != null && !"".equals(basicAuthCred)) {
					client.addAuthorizationHeader(basicAuthCred)
				}
				logDebug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload, isDebugLogEnabled)
				APIResponse response = client.httpPut(payload)
				utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpPut to AAI")
				
				responseData = response.getResponseBodyAsString()
				execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', response.getStatusCode())
				execution.setVariable('PUAAIVfMod_updateVfModuleResponse', responseData)
				logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
				logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
				utils.logAudit("PrepareUpdateAAIVfModule: AAI Response : " + responseData)
				utils.logAudit("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode())
				
				// Set the output for this flow.  The updated VfModule is an output, the generic VNF name, and for
				// backward compatibilty, the heat-stack-id is an output
				execution.setVariable('PUAAIVfMod_outVfModule', newVfModule)
				def vnfName = execution.getVariable('PUAAIVfMod_vnfName')
				logDebug('Output PUAAIVfMod_vnfName set to ' + vnfName, isDebugLogEnabled)
				// TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
				execution.setVariable('WorkflowResponse', newVfModule)
				logDebug('Output PUAAIVfMod_outVfModule set for VF Module Id \'' + newVfModule.getElementText('vf-module-id') + '\'', isDebugLogEnabled)
				def heatStackId = newVfModule.getElementText('heat-stack-id')
				execution.setVariable('PUAAIVfMod_heatStackId', heatStackId)
				logDebug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'', isDebugLogEnabled)
			} catch (Exception ex) {
				ex.printStackTrace()
				logDebug('Exception occurred while executing AAI PUT:' + ex.getMessage(), isDebugLogEnabled)
				execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500)
				execution.setVariable('PUAAIVfMod_updateVfModuleResponse', 'AAI PUT Failed:' + ex.getMessage())
			}
			logDebug('Exited ' + method, isDebugLogEnabled)
		} catch (BpmnError e) {
			throw e;
		} catch (Exception e) {
			logError('Caught exception in ' + method, e)
			createWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage())
		}				
	}
		
	/**
	 * Generates a WorkflowException if the AAI query returns a response code other than 200.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void handleVnfNotFound(Execution execution) {
		def method = getClass().getSimpleName() + '.handleVnfNotFound(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)

		logError('Error occurred attempting to query AAI, Response Code ' +
			execution.getVariable('PUAAIVfMod_getVnfResponseCode') + ', Error Response ' +
			execution.getVariable('PUAAIVfMod_getVnfResponse'))
		String processKey = getProcessKey(execution);
		WorkflowException exception = new WorkflowException(processKey, 5000,
			execution.getVariable('PUAAIVfMod_getVnfResponse'))
		execution.setVariable('WorkflowException', exception)
		
		logDebug('Exited ' + method, isDebugLogEnabled)
	}
	
	/**
	 * Generates a WorkflowException if the VF Module does not pass validation.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void handleVfModuleValidationError(Execution execution) {
		def method = getClass().getSimpleName() + '.handleVfModuleValidationError(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)
				
		def String errorMsg = 'VF Module validation error: ' + execution.getVariable('PUAAIVfMod_vfModuleValidationError')
		logError(errorMsg)
		utils.logAudit("PrepareUpdateAAIVfModule: Error Message : " + errorMsg)
		
		String processKey = getProcessKey(execution);
		WorkflowException exception = new WorkflowException(processKey, 5000, errorMsg)
		execution.setVariable('WorkflowException', exception)

		logDebug('Exited ' + method, isDebugLogEnabled)
	}
	
	/**
	 * Generates a WorkflowException if updating a VF Module in AAI returns a response code other than 200.
	 * 
	 * @param execution The flow's execution instance.
	 */
	public void handleUpdateVfModuleFailure(Execution execution) {
		def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' +
			'execution=' + execution.getId() +
			')'
		def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
		logDebug('Entered ' + method, isDebugLogEnabled)

		logError('Error occurred attempting to update VF Module in AAI, Response Code ' +
			execution.getVariable('PUAAIVfMod_updateVfModuleResponseCode') + ', Error Response ' +
			execution.getVariable('PUAAIVfMod_updateVfModuleResponse'))
		String processKey = getProcessKey(execution);
		WorkflowException exception = new WorkflowException(processKey, 5000,
			execution.getVariable('PUAAIVfMod_updateVfModuleResponse'))
		execution.setVariable('WorkflowException', exception)
		
		logDebug('Exited ' + method, isDebugLogEnabled)
	}
}