aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy
blob: 48ca2905c12f7ee830aecc984fc37caf0e6e133c (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
/*-
 * ============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.infrastructure.scripts

import org.openecomp.mso.bpmn.common.scripts.AaiUtil;
import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil;
import org.openecomp.mso.bpmn.common.scripts.VidUtils;
import org.openecomp.mso.bpmn.core.WorkflowException
import org.openecomp.mso.rest.APIResponse

import groovy.json.JsonSlurper

import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.runtime.Execution;
import org.apache.commons.lang3.*

class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor {

	public static final String  prefix='CVMVINFRAV1_'

	/**
	 * Perform initial processing, such as request validation, initialization of variables, etc.
	 * * @param execution
	 */
	public void preProcessRequest (Execution execution) {
		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
		preProcessRequest(execution, isDebugEnabled)
	}


	/**
	 * Perform initial processing, such as request validation, initialization of variables, etc.
	 * @param execution
	 * @param isDebugEnabled
	 */
	public void preProcessRequest (Execution execution, isDebugEnabled) {

		execution.setVariable("prefix",prefix)
		setSuccessIndicator(execution, false)
		execution.setVariable(prefix+'syncResponseSent', false)

		String createVolumeIncoming = validateRequest(execution, 'vnfId')
		utils.logAudit(createVolumeIncoming)

		try {
			def jsonSlurper = new JsonSlurper()
			Map reqMap = jsonSlurper.parseText(createVolumeIncoming)

			def serviceInstanceId = execution.getVariable('serviceInstanceId')
			def vnfId = execution.getVariable('vnfId')

			def vidUtils = new VidUtils(this)
			createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'CREATE_VF_MODULE_VOL', serviceInstanceId)

			execution.setVariable(prefix+'Request', createVolumeIncoming)
			execution.setVariable(prefix+'vnfId', vnfId)
			execution.setVariable(prefix+'isVidRequest', true)

			utils.log("DEBUG", "XML request:\n" + createVolumeIncoming, isDebugEnabled)

		}
		catch(groovy.json.JsonException je) {
			(new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'Request is not a valid JSON document')
		}

		execution.setVariable(prefix+'source', utils.getNodeText1(createVolumeIncoming, "source"))
		execution.setVariable(prefix+'volumeGroupName', utils.getNodeText1(createVolumeIncoming, 'volume-group-name'))
		execution.setVariable(prefix+'volumeOutputs', utils.getNodeXml(createVolumeIncoming, 'volume-outputs', false))

		execution.setVariable(prefix+'serviceType', 'service-instance')
		execution.setVariable(prefix+'serviceInstanceId', utils.getNodeText1(createVolumeIncoming, "service-instance-id"))

		// Generate volume group id
		String volumeGroupId = UUID.randomUUID()
		utils.log("DEBUG", "Generated volume group id: " + volumeGroupId, isDebugEnabled)

		def testGroupId = execution.getVariable('test-volume-group-id')
		if (testGroupId != null && testGroupId.trim() != '') {
			volumeGroupId = testGroupId
		}

		execution.setVariable(prefix+'volumeGroupId', volumeGroupId)

	}


	public void sendSyncResponse (Execution execution, isDebugEnabled) {
		def volumeGroupId = execution.getVariable(prefix+'volumeGroupId')
		def requestId = execution.getVariable("mso-request-id")
		def serviceInstanceId = execution.getVariable("serviceInstanceId")

		String syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim()

		utils.log("DEBUG", "Sync Response: " + "\n" + syncResponse, isDebugEnabled)
		sendWorkflowResponse(execution, 200, syncResponse)

		execution.setVariable(prefix+'syncResponseSent', true)
	}


	public void sendSyncError (Execution execution, isDebugEnabled) {
		WorkflowException we = execution.getVariable('WorkflowException')
		def errorCode = we?.getErrorCode()
		def errorMessage = we?.getErrorMessage()
		//default to 400 since only invalid request will trigger this method
		sendWorkflowResponse(execution, 400, errorMessage)
	}


	/**
	 * Create a WorkflowException
	 * @param execution
	 * @param isDebugEnabled
	 */
	public void buildWorkflowException(Execution execution, int errorCode, errorMessage, isDebugEnabled) {
		utils.log("DEBUG", errorMessage, isDebugEnabled)
		(new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage)
	}


	public void prepareDbInfraSuccessRequest(Execution execution, isDebugEnabled) {
		def dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs')
		def requestId = execution.getVariable('mso-request-id')
		def statusMessage = "VolumeGroup successfully created."
		def requestStatus = "COMPLETED"
		def progress = "100"

		try {
			String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth")
			utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled)
			
			def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey"))
			execution.setVariable("BasicAuthHeaderValueDB",encodedString)
		} catch (IOException ex) {
			String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
			utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
			exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
		}
		
		/*
		from: $gVolumeGroup/aai:volume-group-id/text()
		to: vnfreq:volume-outputs/vnfreq:volume-group-id
		*/
		// for now assume, generated volumeGroupId is accepted
		def volumeGroupId = execution.getVariable(prefix+'volumeGroupId')

		String dbRequest =
			"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
				<soapenv:Header/>
				<soapenv:Body>
					<ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
						<requestId>${requestId}</requestId>
						<lastModifiedBy>BPMN</lastModifiedBy>
						<statusMessage>${statusMessage}</statusMessage>
						<responseBody></responseBody>
						<requestStatus>${requestStatus}</requestStatus>
						<progress>${progress}</progress>
						<vnfOutputs>${dbVnfOutputs}</vnfOutputs>
						<volumeGroupId>${volumeGroupId}</volumeGroupId>
					</ns:updateInfraRequest>
			   	</soapenv:Body>
			   </soapenv:Envelope>"""

		String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
		execution.setVariable(prefix+"createDBRequest", buildDeleteDBRequestAsString)

		utils.logAudit(buildDeleteDBRequestAsString)
	}





	public void postProcessResponse (Execution execution, isDebugEnabled) {

		def dbReturnCode = execution.getVariable(prefix+'dbReturnCode')
		def createDBResponse =  execution.getVariable(prefix+'createDBResponse')

		utils.logAudit('DB return code: ' + dbReturnCode)
		utils.logAudit('DB response: ' + createDBResponse)

		def requestId = execution.getVariable("mso-request-id")
		def source = execution.getVariable(prefix+'source')

		String msoCompletionRequest =
			"""<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
							xmlns:ns="http://org.openecomp/mso/request/types/v1">
					<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
						<request-id>${requestId}</request-id>
						<action>CREATE</action>
						<source>${source}</source>
		   			</request-info>
					<aetgt:status-message>Volume Group has been created successfully.</aetgt:status-message>
		   			<aetgt:mso-bpel-name>BPMN VF Module Volume action: CREATE</aetgt:mso-bpel-name>
				</aetgt:MsoCompletionRequest>"""

		String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)

		utils.logAudit(createDBResponse)
		utils.logAudit(xmlMsoCompletionRequest)
		execution.setVariable(prefix+'Success', true)
		execution.setVariable(prefix+'CompleteMsoProcessRequest', xmlMsoCompletionRequest)
		utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)

	}

	public void prepareFalloutHandlerRequest(Execution execution, isDebugEnabled) {

		WorkflowException we = execution.getVariable('WorkflowException')
		def errorCode = we?.getErrorCode()
		def errorMessage = we?.getErrorMessage()

		def requestId = execution.getVariable("mso-request-id")
		def source = execution.getVariable(prefix+'source')

		String falloutHandlerRequest =
			"""<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
				                             xmlns:ns="http://org.openecomp/mso/request/types/v1"
				                             xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
				   <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
				      <request-id>${requestId}</request-id>
				      <action>CREATE</action>
				      <source>${source}</source>
				   </request-info>
					   <aetgt:WorkflowException>
					      <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
					      <aetgt:ErrorCode>${errorCode}</aetgt:ErrorCode>
						</aetgt:WorkflowException>

				</aetgt:FalloutHandlerRequest>"""

		// Format Response
		String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest)
		utils.logAudit(xmlHandlerRequest)

		execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest)
		utils.log("ERROR", "Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled)
	}


	/**
	 * Query AAI service instance
	 * @param execution
	 * @param isDebugEnabled
	 */
	public void callRESTQueryAAIServiceInstance(Execution execution, isDebugEnabled) {

		def request = execution.getVariable(prefix+"Request")
		def serviceInstanceId = utils.getNodeText1(request, "service-instance-id")

		AaiUtil aaiUtil = new AaiUtil(this)
		String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution)

		def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId
		utils.logAudit("AAI query service instance request: " + queryAAIRequest)

		APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest)

		String returnCode = response.getStatusCode()
		String aaiResponseAsString = response.getResponseBodyAsString()
		aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)

		utils.logAudit("AAI query service instance return code: " + returnCode)
		utils.logAudit("AAI query service instance response: " + aaiResponseAsString)

		utils.log("DEBUG", "AAI query service instance return code: " + returnCode, isDebugEnabled)
		utils.log("DEBUG", "AAI query service instance response: " + aaiResponseAsString, isDebugEnabled)

		ExceptionUtil exceptionUtil = new ExceptionUtil()

		if (returnCode=='200') {
			utils.log("DEBUG", 'Service instance ' + serviceInstanceId + ' found in AAI.', isDebugEnabled)
		} else {
			if (returnCode=='404') {
				def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.'
				utils.log("DEBUG", message, isDebugEnabled)
				exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message)
			} else {
				WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
				throw new BpmnError("MSOWorkflowException")
			}
		}
	}
}