Groovy scripts header correction
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateVfModuleVolumeInfraV1.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.openecomp.mso.bpmn.infrastructure.scripts
22
23 import org.openecomp.mso.bpmn.common.scripts.AaiUtil;
24 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
25 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil;
26 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
27 import org.openecomp.mso.bpmn.core.WorkflowException
28 import org.openecomp.mso.rest.APIResponse
29 import java.util.Map;
30
31 import groovy.json.JsonOutput
32 import groovy.json.JsonSlurper
33
34 import org.camunda.bpm.engine.delegate.BpmnError
35 import org.camunda.bpm.engine.runtime.Execution;
36 import org.apache.commons.lang3.*
37
38 class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor {
39
40         public static final String  prefix='CVMVINFRAV1_'
41
42         /**
43          * Perform initial processing, such as request validation, initialization of variables, etc.
44          * * @param execution
45          */
46         public void preProcessRequest (Execution execution) {
47                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
48                 setBasicDBAuthHeader(execution, isDebugEnabled)
49                 preProcessRequest(execution, isDebugEnabled)
50         }
51
52
53         /**
54          * Perform initial processing, such as request validation, initialization of variables, etc.
55          * @param execution
56          * @param isDebugEnabled
57          */
58         public void preProcessRequest (Execution execution, isDebugEnabled) {
59
60                 execution.setVariable("prefix",prefix)
61                 setSuccessIndicator(execution, false)
62                 execution.setVariable(prefix+'syncResponseSent', false)
63
64                 String createVolumeIncoming = validateRequest(execution, 'vnfId')
65                 utils.logAudit(createVolumeIncoming)
66
67                 try {
68                         def jsonSlurper = new JsonSlurper()
69                         Map reqMap = jsonSlurper.parseText(createVolumeIncoming)
70                         setupVariables(execution, reqMap, isDebugEnabled)
71                         utils.log("DEBUG", "XML request:\n" + createVolumeIncoming, isDebugEnabled)
72                 }
73                 catch(groovy.json.JsonException je) {
74                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'Request is not a valid JSON document')
75                 }
76
77                 // For rollback in this flow
78                 setBasicDBAuthHeader(execution, isDebugEnabled)
79                 setRollbackEnabled(execution, isDebugEnabled)
80         }
81
82         
83         /**
84          * Set up variables that will be passed to the BB DoCreatevfModuleVolume flow 
85          * @param execution
86          * @param requestMap
87          * @param serviceInstanceId
88          * @param isDebugLogEnabled
89          */
90         public void setupVariables(Execution execution, Map requestMap, isDebugLogEnabled) {
91                 
92                 def jsonOutput = new JsonOutput()
93                 
94                 // volumeGroupId - is generated
95                 String volumeGroupId = UUID.randomUUID()
96                 execution.setVariable('volumeGroupId', volumeGroupId)
97                 utils.log("DEBUG", "Generated volumeGroupId: " + volumeGroupId, isDebugLogEnabled)
98                 
99                 // volumeGroupName
100                 def volGrpName = requestMap.requestDetails.requestInfo?.instanceName ?: ''
101                 execution.setVariable('volumeGroupName', volGrpName)
102
103                 // vfModuleModelInfo
104                 def vfModuleModelInfo = jsonOutput.toJson(requestMap.requestDetails?.modelInfo)
105                 execution.setVariable('vfModuleModelInfo', vfModuleModelInfo)
106                 
107                 // lcpCloudRegonId
108                 def lcpCloudRegionId = requestMap.requestDetails.cloudConfiguration.lcpCloudRegionId
109                 execution.setVariable('lcpCloudRegionId', lcpCloudRegionId)
110                 
111                 // tenant
112                 def tenantId = requestMap.requestDetails.cloudConfiguration.tenantId
113                 execution.setVariable('tenantId', tenantId)
114                 
115                 // source
116                 def source = requestMap.requestDetails.requestInfo.source
117                 execution.setVariable(prefix+'source', source)
118                 
119                 // vnfType and asdcServiceModelVersion
120                 
121                 def serviceName = ''
122                 def asdcServiceModelVersion = ''
123                 def modelCustomizationName = ''
124                 
125                 def relatedInstanceList = requestMap.requestDetails.relatedInstanceList
126                 relatedInstanceList.each {
127                         if (it.relatedInstance.modelInfo?.modelType == 'service') {
128                                 serviceName = it.relatedInstance.modelInfo?.modelName
129                                 asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
130                         }
131                         if (it.relatedInstance.modelInfo?.modelType == 'vnf') {
132                                 modelCustomizationName = it.relatedInstance.modelInfo?.modelCustomizationName
133                         }
134                 }
135                 
136                 def vnfType = serviceName + '/' + modelCustomizationName
137                 execution.setVariable('vnfType', vnfType)
138                 execution.setVariable('asdcServiceModelVersion', asdcServiceModelVersion)
139                 
140                 // vfModuleInputParams
141                 def userParams = requestMap.requestDetails?.requestParameters?.userParams
142                 Map<String, String> vfModuleInputMap = [:]
143                 
144                 userParams.each { userParam ->
145                         vfModuleInputMap.put(userParam.name, userParam.value)
146                 }
147                 execution.setVariable('vfModuleInputParams', vfModuleInputMap)
148
149                 // disableRollback (true or false)
150                 def disableRollback = requestMap.requestDetails.requestInfo.suppressRollback
151                 execution.setVariable('disableRollback', disableRollback)
152                 utils.log("DEBUG", 'disableRollback (suppressRollback) from request: ' + disableRollback, isDebugLogEnabled)
153                 
154         }
155
156         
157         
158         public void sendSyncResponse (Execution execution, isDebugEnabled) {
159                 def volumeGroupId = execution.getVariable('volumeGroupId')
160                 def requestId = execution.getVariable("mso-request-id")
161                 def serviceInstanceId = execution.getVariable("serviceInstanceId")
162
163                 String syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim()
164
165                 utils.log("DEBUG", "Sync Response: " + "\n" + syncResponse, isDebugEnabled)
166                 sendWorkflowResponse(execution, 200, syncResponse)
167
168                 execution.setVariable(prefix+'syncResponseSent', true)
169         }
170
171
172         public void sendSyncError (Execution execution, isDebugEnabled) {
173                 WorkflowException we = execution.getVariable('WorkflowException')
174                 def errorCode = we?.getErrorCode()
175                 def errorMessage = we?.getErrorMessage()
176                 //default to 400 since only invalid request will trigger this method
177                 sendWorkflowResponse(execution, 400, errorMessage)
178         }
179
180
181         /**
182          * Create a WorkflowException
183          * @param execution
184          * @param isDebugEnabled
185          */
186         public void buildWorkflowException(Execution execution, int errorCode, errorMessage, isDebugEnabled) {
187                 utils.log("DEBUG", errorMessage, isDebugEnabled)
188                 (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage)
189         }
190
191
192         /**
193          * Build Infra DB Request
194          * @param execution
195          * @param isDebugEnabled
196          */
197         public void prepareDbInfraSuccessRequest(Execution execution, isDebugEnabled) {
198                 def dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs')
199                 def requestId = execution.getVariable('mso-request-id')
200                 def statusMessage = "VolumeGroup successfully created."
201                 def requestStatus = "COMPLETED"
202                 def progress = "100"
203                 
204                 /*
205                 from: $gVolumeGroup/aai:volume-group-id/text()
206                 to: vnfreq:volume-outputs/vnfreq:volume-group-id
207                 */
208                 // for now assume, generated volumeGroupId is accepted
209                 def volumeGroupId = execution.getVariable(prefix+'volumeGroupId')
210
211                 String dbRequest =
212                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
213                                 <soapenv:Header/>
214                                 <soapenv:Body>
215                                         <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
216                                                 <requestId>${requestId}</requestId>
217                                                 <lastModifiedBy>BPMN</lastModifiedBy>
218                                                 <statusMessage>${statusMessage}</statusMessage>
219                                                 <responseBody></responseBody>
220                                                 <requestStatus>${requestStatus}</requestStatus>
221                                                 <progress>${progress}</progress>
222                                                 <vnfOutputs>${dbVnfOutputs}</vnfOutputs>
223                                                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
224                                         </ns:updateInfraRequest>
225                                 </soapenv:Body>
226                            </soapenv:Envelope>"""
227
228                 String buildDBRequestAsString = utils.formatXml(dbRequest)
229                 execution.setVariable(prefix+"createDBRequest", buildDBRequestAsString)
230                 utils.log("DEBUG", "DB Infra Request: " + buildDBRequestAsString, isDebugEnabled)
231                 utils.logAudit(buildDBRequestAsString)
232         }
233
234
235         /**
236          * Build CommpleteMsoProcess request
237          * @param execution
238          * @param isDebugEnabled
239          */
240         public void postProcessResponse (Execution execution, isDebugEnabled) {
241
242                 def dbReturnCode = execution.getVariable(prefix+'dbReturnCode')
243                 def createDBResponse =  execution.getVariable(prefix+'createDBResponse')
244
245                 utils.logAudit('DB return code: ' + dbReturnCode)
246                 utils.logAudit('DB response: ' + createDBResponse)
247
248                 def requestId = execution.getVariable("mso-request-id")
249                 def source = execution.getVariable(prefix+'source')
250
251                 String msoCompletionRequest =
252                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
253                                                         xmlns:ns="http://org.openecomp/mso/request/types/v1">
254                                         <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
255                                                 <request-id>${requestId}</request-id>
256                                                 <action>CREATE</action>
257                                                 <source>${source}</source>
258                                         </request-info>
259                                         <aetgt:status-message>Volume Group has been created successfully.</aetgt:status-message>
260                                         <aetgt:mso-bpel-name>BPMN VF Module Volume action: CREATE</aetgt:mso-bpel-name>
261                                 </aetgt:MsoCompletionRequest>"""
262
263                 String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
264
265                 utils.logAudit(createDBResponse)
266                 utils.logAudit(xmlMsoCompletionRequest)
267                 execution.setVariable(prefix+'Success', true)
268                 execution.setVariable(prefix+'CompleteMsoProcessRequest', xmlMsoCompletionRequest)
269                 utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
270
271         }
272
273         public void prepareFalloutHandlerRequest(Execution execution, isDebugEnabled) {
274
275                 WorkflowException we = execution.getVariable('WorkflowException')
276                 def errorCode = we?.getErrorCode()
277                 def errorMessage = we?.getErrorMessage()
278
279                 def requestId = execution.getVariable("mso-request-id")
280                 def source = execution.getVariable(prefix+'source')
281
282                 String falloutHandlerRequest =
283                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
284                                                              xmlns:ns="http://org.openecomp/mso/request/types/v1"
285                                                              xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
286                                    <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
287                                       <request-id>${requestId}</request-id>
288                                       <action>CREATE</action>
289                                       <source>${source}</source>
290                                    </request-info>
291                                            <aetgt:WorkflowException>
292                                               <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
293                                               <aetgt:ErrorCode>${errorCode}</aetgt:ErrorCode>
294                                                 </aetgt:WorkflowException>
295
296                                 </aetgt:FalloutHandlerRequest>"""
297
298                 // Format Response
299                 String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest)
300                 utils.logAudit(xmlHandlerRequest)
301
302                 execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest)
303                 utils.log("ERROR", "Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled)
304         }
305
306
307         /**
308          * Query AAI service instance
309          * @param execution
310          * @param isDebugEnabled
311          */
312         public void callRESTQueryAAIServiceInstance(Execution execution, isDebugEnabled) {
313
314                 def request = execution.getVariable(prefix+"Request")
315                 def serviceInstanceId = utils.getNodeText1(request, "service-instance-id")
316
317                 AaiUtil aaiUtil = new AaiUtil(this)
318                 String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution)
319
320                 def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId
321                 utils.logAudit("AAI query service instance request: " + queryAAIRequest)
322
323                 APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest)
324
325                 String returnCode = response.getStatusCode()
326                 String aaiResponseAsString = response.getResponseBodyAsString()
327                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
328
329                 utils.logAudit("AAI query service instance return code: " + returnCode)
330                 utils.logAudit("AAI query service instance response: " + aaiResponseAsString)
331
332                 utils.log("DEBUG", "AAI query service instance return code: " + returnCode, isDebugEnabled)
333                 utils.log("DEBUG", "AAI query service instance response: " + aaiResponseAsString, isDebugEnabled)
334
335                 ExceptionUtil exceptionUtil = new ExceptionUtil()
336
337                 if (returnCode=='200') {
338                         utils.log("DEBUG", 'Service instance ' + serviceInstanceId + ' found in AAI.', isDebugEnabled)
339                 } else {
340                         if (returnCode=='404') {
341                                 def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.'
342                                 utils.log("DEBUG", message, isDebugEnabled)
343                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message)
344                         } else {
345                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
346                                 throw new BpmnError("MSOWorkflowException")
347                         }
348                 }
349         }
350         
351         public void logAndSaveOriginalException(Execution execution, isDebugLogEnabled) {
352                 logWorkflowException(execution, 'CreateVfModuleVolumeInfraV1 caught an event')
353                 saveWorkflowException(execution, 'CVMVINFRAV1_originalWorkflowException')
354         }
355         
356         public void validateRollbackResponse(Execution execution, isDebugLogEnabled) {
357
358                 def originalException = execution.getVariable("CVMVINFRAV1_originalWorkflowException")
359                 execution.setVariable("WorkflowException", originalException)
360                 execution.setVariable("RollbackCompleted", true)
361
362         }
363 }