Removed MsoLogger class
[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  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
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.entities.uri.AAIResourceUri
33 import org.onap.so.client.aai.entities.uri.AAIUriFactory
34 import org.onap.so.logger.ErrorCode
35 import org.onap.so.logger.MessageEnum
36 import org.slf4j.Logger
37 import org.slf4j.LoggerFactory
38
39 import groovy.json.JsonOutput
40 import groovy.json.JsonSlurper
41
42
43 class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor {
44         
45     private static final Logger logger = LoggerFactory.getLogger( 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                 logger.debug(createVolumeIncoming)
72
73                 try {
74                         def jsonSlurper = new JsonSlurper()
75                         Map reqMap = jsonSlurper.parseText(createVolumeIncoming)
76                         setupVariables(execution, reqMap, isDebugEnabled)
77                         logger.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                 logger.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                 logger.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                 logger.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                 logger.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                 logger.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                 logger.debug('DB return code: ' + dbReturnCode)
255                 logger.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                 logger.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                 logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Overall Error Response " +
310                                 "going to FalloutHandler", "BPMN", ErrorCode.UnknownError.getValue(), "\n" + xmlHandlerRequest);
311         }
312
313
314         /**
315          * Query AAI service instance
316          * @param execution
317          * @param isDebugEnabled
318          */
319         public void callRESTQueryAAIServiceInstance(DelegateExecution execution, isDebugEnabled) {
320
321                 def request = execution.getVariable(prefix+"Request")
322                 def serviceInstanceId = utils.getNodeText(request, "service-instance-id")
323                 ExceptionUtil exceptionUtil = new ExceptionUtil()
324                 try {
325
326                         AAIResourceUri uri = AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE,serviceInstanceId)
327                         if(getAAIClient().exists(uri)){
328                                 logger.debug('Service instance ' + serviceInstanceId + ' found in AAI.')
329                         }else{
330                                 def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.'
331                                 logger.debug(message)
332                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message)
333                         }
334                 }catch(BpmnError bpmnError){
335                         throw bpmnError
336                 }catch(Exception ex){
337                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, ex.getMessage())
338                 }
339         }
340         
341         public void logAndSaveOriginalException(DelegateExecution execution, isDebugLogEnabled) {
342                 logWorkflowException(execution, 'CreateVfModuleVolumeInfraV1 caught an event')
343                 saveWorkflowException(execution, 'CVMVINFRAV1_originalWorkflowException')
344         }
345         
346         public void validateRollbackResponse(DelegateExecution execution, isDebugLogEnabled) {
347
348                 def originalException = execution.getVariable("CVMVINFRAV1_originalWorkflowException")
349                 execution.setVariable("WorkflowException", originalException)
350                 execution.setVariable("RollbackCompleted", true)
351
352         }
353 }