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