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