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