Cleaned up content of MsoLogger
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / UpdateVfModuleInfra.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 groovy.json.JsonOutput
26 import groovy.json.JsonSlurper
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
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.logger.MessageEnum
34 import org.onap.so.logger.MsoLogger
35 import org.slf4j.Logger
36 import org.slf4j.LoggerFactory
37
38 public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor {
39     private static final Logger logger = LoggerFactory.getLogger(UpdateVfModuleInfra.class)
40
41         ExceptionUtil exceptionUtil = new ExceptionUtil()
42
43         /**
44          * Initialize the flow's variables.
45          *
46          * @param execution The flow's execution instance.
47          */
48         public void initProcessVariables(DelegateExecution execution) {
49                 execution.setVariable('prefix', 'UPDVfModI_')
50                 execution.setVariable('UPDVfModI_Request', null)
51                 execution.setVariable('UPDVfModI_requestInfo', null)
52                 execution.setVariable('UPDVfModI_requestId', null)
53                 execution.setVariable('UPDVfModI_source', null)
54                 execution.setVariable('UPDVfModI_vnfInputs', null)
55                 execution.setVariable('UPDVfModI_vnfId', null)
56                 execution.setVariable('UPDVfModI_vfModuleId', null)
57                 execution.setVariable('UPDVfModI_tenantId', null)
58                 execution.setVariable('UPDVfModI_volumeGroupId', null)
59                 execution.setVariable('UPDVfModI_vnfParams', null)
60                 execution.setVariable('UPDVfModI_updateInfraRequest', null)
61                 execution.setVariable('UpdateVfModuleSuccessIndicator', false)
62         }
63
64         /**
65          * Check for missing elements in the received request.
66          *
67          * @param execution The flow's execution instance.
68          */
69         public void preProcessRequest(DelegateExecution execution) {
70                 
71                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
72                 'execution=' + execution.getId() +
73                 ')'
74
75         logger.trace('Entered {}', method)
76
77                 initProcessVariables(execution)
78
79                 def prefix = "UPDVfModI_"               
80
81                 def incomingRequest = execution.getVariable('bpmnRequest')
82
83         logger.debug("Incoming Infra Request: {}", incomingRequest)
84                 try {
85                         def jsonSlurper = new JsonSlurper()
86                         def jsonOutput = new JsonOutput()
87                         Map reqMap = jsonSlurper.parseText(incomingRequest)
88             logger.debug(" Request is in JSON format.")
89
90                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
91                         def vnfId = execution.getVariable('vnfId')
92                         
93                         execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId)
94                         execution.setVariable(prefix+'vnfId', vnfId)
95                         execution.setVariable("isVidRequest", "true")
96                         
97                         def vnfName = ''
98                         def asdcServiceModelVersion = ''
99                         def serviceModelInfo = null
100                         def vnfModelInfo = null
101                         
102                         def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList
103                                                 
104                         if (relatedInstanceList != null) {
105                                 relatedInstanceList.each {
106                                         if (it.relatedInstance.modelInfo?.modelType == 'service') {
107                                                 asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
108                                                 serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
109                                                 
110                                         }
111                                         if (it.relatedInstance.modelInfo.modelType == 'vnf') {
112                                                 vnfName = it.relatedInstance.instanceName ?: ''
113                                                 vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
114                                         }
115                                 }
116                         }
117                         
118                         execution.setVariable(prefix + 'vnfName', vnfName)
119                         execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion)
120                         execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo)
121                         execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo)                    
122                         
123                         def vnfType = execution.getVariable('vnfType')
124                         execution.setVariable(prefix + 'vnfType', vnfType)      
125                         def vfModuleId = execution.getVariable('vfModuleId')
126                         execution.setVariable(prefix + 'vfModuleId', vfModuleId)
127                         def volumeGroupId = execution.getVariable('volumeGroupId')
128                         execution.setVariable(prefix + 'volumeGroupId', volumeGroupId)
129                         def userParams = reqMap.requestDetails?.requestParameters?.userParams                                   
130                         
131                         Map<String, String> userParamsMap = [:]
132                         if (userParams != null) {
133                                 userParams.each { userParam ->
134                                         userParamsMap.put(userParam.name, userParam.value.toString())
135                                 }                                                       
136                         }
137
138             logger.debug('Processed user params: {}', userParamsMap)
139                         
140                         execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap)
141                         
142                         def isBaseVfModule = "false"
143                         if (execution.getVariable('isBaseVfModule') == true) {
144                                 isBaseVfModule = "true"
145                         }                       
146                         
147                         execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule)
148                                                 
149                         def requestId = execution.getVariable("mso-request-id")
150                         execution.setVariable(prefix + 'requestId', requestId)
151                         
152                         def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo)
153                         execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo)
154                         
155                         def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback
156                         
157                         
158                         def backoutOnFailure = ""
159                         if(suppressRollback != null){
160                                 if ( suppressRollback == true) {
161                                         backoutOnFailure = "false"
162                                 } else if ( suppressRollback == false) {
163                                         backoutOnFailure = "true"
164                                 }
165                         }
166                         
167                         execution.setVariable('disableRollback', suppressRollback)
168                         
169                         def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null
170                         execution.setVariable(prefix + 'vfModuleName', vfModuleName)
171                         
172                         def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: ''
173                         execution.setVariable(prefix + 'serviceId', serviceId)
174                         
175                         def usePreload = reqMap.requestDetails?.requestParameters?.usePreload
176                         execution.setVariable(prefix + 'usePreload', usePreload)
177                         
178                         def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration
179                         def lcpCloudRegionId    = cloudConfiguration.lcpCloudRegionId
180                         execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId)
181                         
182                         def cloudOwner  = cloudConfiguration.cloudOwner
183                         execution.setVariable(prefix + 'cloudOwner', cloudOwner)
184                         
185                         def tenantId = cloudConfiguration.tenantId
186                         execution.setVariable(prefix + 'tenantId', tenantId)
187                         
188                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
189                         execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId)
190                         
191                         execution.setVariable(prefix + 'sdncVersion', '1702')
192
193                         execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false)
194                                                 
195
196                         
197                         
198                         def source = reqMap.requestDetails?.requestInfo?.source
199                         execution.setVariable(prefix + "source", source)
200                         
201                         //For Completion Handler & Fallout Handler
202                         String requestInfo =
203                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
204                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
205                                         <action>UPDATE</action>
206                                         <source>${MsoUtils.xmlEscape(source)}</source>
207                                    </request-info>"""
208                         
209                         execution.setVariable(prefix + "requestInfo", requestInfo)
210                         
211                         //backoutOnFailure                      
212
213             logger.debug('RequestInfo: {}', execution.getVariable(prefix + "requestInfo"))
214
215             logger.trace('Exited {}', method)
216
217                 }
218                 catch(groovy.json.JsonException je) {
219             logger.debug(" Request is not in JSON format.")
220                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
221
222                 }
223                 catch(Exception e) {
224                         String restFaultMessage = e.getMessage()
225             logger.error("{} {} Exception Encountered - \n{}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
226                     MsoLogger.ErrorCode.UnknownError.getValue(), restFaultMessage, e)
227                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
228                 }       
229         }
230
231         /**
232          * Prepare and send the sychronous response for this flow.
233          *
234          * @param execution The flow's execution instance.
235          */
236         public void sendSynchResponse(DelegateExecution execution) {
237                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
238                         'execution=' + execution.getId() +
239                         ')'
240
241         logger.trace('Entered {}', method)
242
243                 try {
244                         def requestInfo = execution.getVariable('UPDVfModI_requestInfo')
245                         def requestId = execution.getVariable('UPDVfModI_requestId')
246                         def source = execution.getVariable('UPDVfModI_source')
247                         def progress = getNodeTextForce(requestInfo, 'progress')
248                         if (progress.isEmpty()) {
249                                 progress = '0'
250                         }
251                         def startTime = getNodeTextForce(requestInfo, 'start-time')
252                         if (startTime.isEmpty()) {
253                                 startTime = System.currentTimeMillis()
254                         }
255
256                         // RESTResponse (for API Handler (APIH) Reply Task)
257                         def vfModuleId = execution.getVariable("vfModuleId")
258                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
259
260                         sendWorkflowResponse(execution, 200, synchResponse)
261
262             logger.trace('Exited {}', method)
263                 } catch (BpmnError e) {
264                         throw e;
265                 } catch (Exception e) {
266             logger.error("{} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
267                     MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
268                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
269                 }
270         }
271
272         /**
273          * Prepare the Request for invoking the DoUpdateVfModule subflow.
274          *
275          * NOTE: Currently, the method just logs passing through as the
276          * incoming Request to this main flow is used as the Request to
277          * the DoUpdateVfModule subflow. No preparation processing is
278          * necessary.
279          *
280          * @param execution The flow's execution instance.
281          */
282         public void prepDoUpdateVfModule(DelegateExecution execution) {
283                 def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' +
284                         'execution=' + execution.getId() +
285                         ')'
286
287         logger.trace('Entered {}', method)
288
289                 try {
290
291             logger.trace('Exited {}', method)
292                 } catch (BpmnError e) {
293                         throw e;
294                 } catch (Exception e) {
295             logger.error("{} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
296                     MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
297                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage())
298                 }
299         }
300
301         /**
302          * Prepare the Request for updating the DB for this Infra Request.
303          *
304          * @param execution The flow's execution instance.
305          */
306         public void prepUpdateInfraRequest(DelegateExecution execution) {
307                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
308                         'execution=' + execution.getId() +
309                         ')'
310
311         logger.trace('Entered {}', method)
312
313                 try {
314                         def requestId = execution.getVariable('UPDVfModI_requestId')
315                         def vnfId = execution.getVariable('UPDVfModI_vnfId')
316                         def vfModuleId = execution.getVariable('UPDVfModI_vfModuleId')
317                         def tenantId = execution.getVariable('UPDVfModI_tenantId')
318                         def volumeGroupId = execution.getVariable('UPDVfModI_volumeGroupId')
319
320                         String updateInfraRequest = """
321                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
322                                                 xmlns:req="http://org.onap.so/requestsdb">
323                                         <soapenv:Header/>
324                                         <soapenv:Body>
325                                                 <req:updateInfraRequest>
326                                                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
327                                                         <lastModifiedBy>BPEL</lastModifiedBy>
328                                                         <requestStatus>COMPLETE</requestStatus>
329                                                         <progress>100</progress>
330                                                         <vnfOutputs>
331                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
332                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
333                                                                 <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id>
334                                                                 <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id>
335                                                         </vnfOutputs>
336                                                 </req:updateInfraRequest>
337                                         </soapenv:Body>
338                                 </soapenv:Envelope>
339                         """
340
341                         updateInfraRequest = utils.formatXml(updateInfraRequest)
342                         execution.setVariable('UPDVfModI_updateInfraRequest', updateInfraRequest)
343             logger.debug('Request for Update Infra Request:\n{}', updateInfraRequest)
344
345             logger.trace('Exited {}', method)
346                 } catch (BpmnError e) {
347                         throw e;
348                 } catch (Exception e) {
349             logger.error("{} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
350                     MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
351                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage())
352                 }
353         }
354
355         /**
356          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
357          *
358          * @param execution the execution
359          * @param resultVar the execution variable in which the result will be stored
360          */
361         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
362                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
363                         'execution=' + execution.getId() +
364                         ', resultVar=' + resultVar +
365                         ')'
366
367         logger.trace('Entered {}', method)
368
369                 try {
370                         def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo')
371
372                         String content = """
373                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
374                                                 xmlns:reqtype="http://org.onap/so/request/types/v1">
375                                         ${requestInfo}
376                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
377                                 </sdncadapterworkflow:MsoCompletionRequest>
378                         """
379
380                         content = utils.formatXml(content)
381             logger.debug('{} = {}{}', resultVar, System.lineSeparator(), content)
382                         execution.setVariable(resultVar, content)
383
384             logger.trace('Exited {}', method)
385                 } catch (BpmnError e) {
386                         throw e;
387                 } catch (Exception e) {
388             logger.error("{} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
389                     MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
390                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
391                 }
392         }
393
394         /**
395          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
396          *
397          * @param execution the execution
398          * @param resultVar the execution variable in which the result will be stored
399          */
400         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
401                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
402                         'execution=' + execution.getId() +
403                         ', resultVar=' + resultVar +
404                         ')'
405
406         logger.trace('Entered {}', method)
407
408                 try {
409                         def prefix = execution.getVariable('prefix')
410                         def request = getVariable(execution, prefix+'Request')
411                         def requestInformation = execution.getVariable(prefix + "requestInfo")
412
413                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
414                         def errorResponseCode = workflowException.getErrorCode()
415                         def errorResponseMsg = workflowException.getErrorMessage()
416                         def encErrorResponseMsg = ""
417                         if (errorResponseMsg != null) {
418                                 encErrorResponseMsg = errorResponseMsg
419                         }
420
421                         String content = """
422                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
423                                                 xmlns:reqtype="http://org.onap/so/request/types/v1"
424                                                 xmlns:msoservtypes="http://org.onap/so/request/types/v1"
425                                                 xmlns:structuredtypes="http://org.onap/so/structured/types/v1">
426                                         ${requestInformation}
427                                         <sdncadapterworkflow:WorkflowException>
428                                                 <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage>
429                                                 <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode>
430                                         </sdncadapterworkflow:WorkflowException>
431                                 </sdncadapterworkflow:FalloutHandlerRequest>
432                         """
433                         content = utils.formatXml(content)
434             logger.debug('{} = {}{}', resultVar, System.lineSeparator(), content)
435                         execution.setVariable(resultVar, content)
436
437             logger.trace('Exited {}', method)
438                 } catch (BpmnError e) {
439                         throw e;
440                 } catch (Exception e) {
441             logger.error("{} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
442                     MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
443                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
444                 }
445         }
446
447         /**
448          * Validates the request, request id and service instance id.  If a problem is found,
449          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
450          * method also sets up the log context for the workflow.
451          * @param execution the execution
452          * @return the validated request
453          */
454         public String validateInfraRequest(DelegateExecution execution) {
455                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
456                         'execution=' + execution.getId() +
457                         ')'
458
459         logger.trace('Entered {}', method)
460
461                 String processKey = getProcessKey(execution);
462                 def prefix = execution.getVariable("prefix")
463
464                 if (prefix == null) {
465                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
466                 }
467
468                 try {
469                         def request = execution.getVariable(prefix + 'Request')
470
471                         if (request == null) {
472                                 request = execution.getVariable(processKey + 'Request')
473
474                                 if (request == null) {
475                                         request = execution.getVariable('bpmnRequest')
476                                 }
477
478                                 setVariable(execution, processKey + 'Request', null);
479                                 setVariable(execution, 'bpmnRequest', null);
480                                 setVariable(execution, prefix + 'Request', request);
481                         }
482
483                         if (request == null) {
484                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
485                         }
486
487                         /*
488
489                         def requestId = execution.getVariable("mso-request-id")
490
491                         if (requestId == null) {
492                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
493                         }
494
495                         setVariable(execution, prefix + 'requestId', requestId)
496
497                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
498
499                         if (serviceInstanceId == null) {
500                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
501                         }
502
503                         utils.logContext(requestId, serviceInstanceId)
504                         */
505             logger.debug('Incoming message: {}{}', System.lineSeparator(), request)
506             logger.trace('Exited {}', method)
507                         return request
508                 } catch (BpmnError e) {
509                         throw e;
510                 } catch (Exception e) {
511             logger.error("{} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
512                     MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
513                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
514                 }
515         }
516
517 }