Cleaned up content of MsoLogger
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DeleteVfModuleInfra.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.common.scripts.VidUtils;
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.json.JsonUtils;
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 import groovy.json.JsonSlurper
39
40
41
42 public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor {
43
44     private static final Logger logger = LoggerFactory.getLogger( DeleteVfModuleInfra.class);
45         ExceptionUtil exceptionUtil = new ExceptionUtil()
46         JsonUtils jsonUtil = new JsonUtils()
47         /**
48          * Initialize the flow's variables.
49          *
50          * @param execution The flow's execution instance.
51          */
52         public void initProcessVariables(DelegateExecution execution) {
53                 execution.setVariable('prefix', 'DELVfModI_')
54                 execution.setVariable('DELVfModI_requestInfo', null)
55                 execution.setVariable('DELVfModI_requestId', null)
56                 execution.setVariable('DELVfModI_source', null)
57                 execution.setVariable('DELVfModI_vnfInputs', null)
58                 execution.setVariable('DELVfModI_vnfId', null)
59                 execution.setVariable('DELVfModI_vfModuleId', null)
60                 execution.setVariable('DELVfModI_tenantId', null)
61                 execution.setVariable('DELVfModI_volumeGroupId', null)
62                 execution.setVariable('DELVfModI_vnfParams', null)
63                 execution.setVariable('DELVfModI_updateInfraRequest', null)
64                 execution.setVariable('DeleteVfModuleRequest', null)
65                 execution.setVariable('DeleteVfModuleSuccessIndicator', false)
66         }
67
68         /**
69          * Process the incoming DELETE_VF_MODULE vnf-request.
70          *
71          * @param execution The flow's execution instance.
72          */
73         public void preProcessRequest(DelegateExecution execution) {
74                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
75                         'execution=' + execution.getId() +
76                         ')'
77                 logger.trace('Entered ' + method)
78                 execution.setVariable("isVidRequest", "false")
79                 initProcessVariables(execution)
80
81                 def prefix = execution.getVariable('prefix')
82
83                 def incomingRequest = execution.getVariable('bpmnRequest')
84                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
85                 
86                 logger.debug("Incoming Infra Request: " + incomingRequest)
87
88                 // check if request is xml or json
89                 try {
90                         def jsonSlurper = new JsonSlurper()
91                         Map reqMap = jsonSlurper.parseText(incomingRequest)
92                         logger.debug(" Request is in JSON format.")
93
94                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
95                         logger.debug("serviceInstanceId is: " + serviceInstanceId)
96                         def vnfId = execution.getVariable('vnfId')
97                         logger.debug("vnfId is: " + vnfId)
98                         def cloudConfiguration = jsonUtil.getJsonValue(incomingRequest, "requestDetails.cloudConfiguration")
99                         execution.setVariable("cloudConfiguration", cloudConfiguration)
100                         logger.debug("CloudConfiguration is: " + cloudConfiguration)
101                         def vfModuleModelInfo = jsonUtil.getJsonValue(incomingRequest, "requestDetails.modelInfo")
102
103                         execution.setVariable("vfModuleModelInfo", vfModuleModelInfo)
104                         logger.debug("VfModuleModelInfo is: " + vfModuleModelInfo)
105                         
106                         // This is aLaCarte flow, so aLaCarte flag is always on
107                         execution.setVariable('aLaCarte', true)
108                         
109                         def vidUtils = new VidUtils(this)
110
111                         String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'DELETE_VF_MODULE', serviceInstanceId)
112
113                         logger.debug(" Request in XML format: " + requestInXmlFormat)
114
115                         setBasicDBAuthHeader(execution, isDebugLogEnabled)
116                         
117                         execution.setVariable(prefix + 'Request', requestInXmlFormat)
118                         execution.setVariable(prefix+'vnfId', vnfId)
119                         execution.setVariable("isVidRequest", "true")
120
121                 }
122                 catch(groovy.json.JsonException je) {
123                         logger.debug(" Request is not in JSON format.")
124                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request")
125
126                 }
127                 catch(Exception e) {
128                         String restFaultMessage = e.getMessage()
129                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception",
130                                         "BPMN", MsoLogger.ErrorCode.UnknownError.getValue(),
131                                         "Exception is:\n" + e);
132                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request")
133                 }
134
135
136                 try {
137
138                         String request = validateRequest(execution)
139                         execution.setVariable('DeleteVfModuleRequest', request)
140                         logger.debug("DeleteVfModuleInfra Request: " + request)
141
142                         def requestInfo = getRequiredNodeXml(execution, request, 'request-info')
143                         execution.setVariable('DELVfModI_requestInfo', requestInfo)
144                         execution.setVariable('DELVfModI_requestId', getRequiredNodeText(execution, requestInfo, 'request-id'))
145                         execution.setVariable('DELVfModI_source', getNodeTextForce(requestInfo, 'source'))
146
147                         def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs')
148                         execution.setVariable('DELVfModI_vnfInputs', vnfInputs)
149                         execution.setVariable('DELVfModI_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id'))
150                         execution.setVariable('DELVfModI_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id'))
151                         execution.setVariable('DELVfModI_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name'))
152                         execution.setVariable('DELVfModI_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id'))
153                         execution.setVariable('DELVfModI_volumeGroupId', getNodeTextForce(vnfInputs, 'volume-group-id'))
154
155                         def vnfParams = utils.getNodeXml(request, 'vnf-params')
156                         execution.setVariable('DELVfModI_vnfParams', vnfParams)
157
158                         logger.trace('Exited ' + method)
159                 } catch (BpmnError e) {
160                         throw e;
161                 } catch (Exception e) {
162                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
163                                         "Caught exception in " + method, "BPMN",
164                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
165                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
166                 }
167         }
168
169         /**
170          * Sends the 'IN_PROGRESS' synchronous response.
171          *
172          * @param execution The flow's execution instance.
173          */
174         public void sendSynchResponse(DelegateExecution execution) {
175                 def method = getClass().getSimpleName() + '.sendResponse(' +
176                         'execution=' + execution.getId() +
177                         ')'
178                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
179                 logger.trace('Entered ' + method)
180
181                 try {
182                         def requestInfo = execution.getVariable('DELVfModI_requestInfo')
183                         def requestId = execution.getVariable('DELVfModI_requestId')
184                         def source = execution.getVariable('DELVfModI_source')
185                         def progress = getNodeTextForce(requestInfo, 'progress')
186                         if (progress.isEmpty()) {
187                                 progress = '0'
188                         }
189                         def startTime = getNodeTextForce(requestInfo, 'start-time')
190                         if (startTime.isEmpty()) {
191                                 startTime = System.currentTimeMillis()
192                         }
193
194                         // RESTResponse (for API Handler (APIH) Reply Task)
195                         def vfModuleId = execution.getVariable('DELVfModI_vfModuleId')
196                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
197
198                         logger.debug("DeleteVfModuleInfra Synch Response: " + synchResponse)
199                         sendWorkflowResponse(execution, 200, synchResponse)
200
201                         logger.trace('Exited ' + method)
202                 } catch (BpmnError e) {
203                         throw e;
204                 } catch (Exception e) {
205                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
206                                         "Caught exception in " + method, "BPMN",
207                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
208                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
209                 }
210         }
211
212         /**
213          * Currently passing the entire DELETE_VF_MODULE vnf-request to DoDeleteVfModule.
214          * 'DeleteVfModuleRequest' is now being set in preProcessRequest().
215          * TBD: may want to eventually create a specific request that only contains the needed fields.
216          *
217          * @param execution The flow's execution instance.
218          */
219         public void prepDoDeleteVfModule(DelegateExecution execution) {
220                 def method = getClass().getSimpleName() + '.prepDoDeleteVfModule(' +
221                         'execution=' + execution.getId() +
222                         ')'
223                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
224                 logger.trace('Entered ' + method)
225
226                 try {
227
228                         logger.trace('Exited ' + method)
229                 } catch (BpmnError e) {
230                         throw e;
231                 } catch (Exception e) {
232                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in '
233                                         + method, "BPMN", MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
234                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage())
235                 }
236         }
237
238         /**
239          * Prepare the DB update to add an entry for the Vf Module request.
240          *
241          * @param execution The flow's execution instance.
242          */
243         public void prepUpdateInfraRequest(DelegateExecution execution) {
244                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
245                         'execution=' + execution.getId() +
246                         ')'
247                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
248                 logger.trace('Entered ' + method)
249
250                 try {
251                         def requestId = execution.getVariable('DELVfModI_requestId')
252                         def vnfId = execution.getVariable('DELVfModI_vnfId')
253                         def vfModuleId = execution.getVariable('DELVfModI_vfModuleId')
254                         def tenantId = execution.getVariable('DELVfModI_tenantId')
255                         def volumeGroupId = execution.getVariable('DELVfModI_volumeGroupId')
256
257                         String updateInfraRequest = """
258                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
259                                         xmlns:req="http://org.onap.so/requestsdb">
260                                         <soapenv:Header/>
261                                         <soapenv:Body>
262                                                 <req:updateInfraRequest>
263                                                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
264                                                         <lastModifiedBy>BPMN</lastModifiedBy>
265                                                         <requestStatus>COMPLETED</requestStatus>
266                                                         <progress>100</progress>
267                                                 </req:updateInfraRequest>
268                                         </soapenv:Body>
269                                 </soapenv:Envelope>
270                         """
271
272                         updateInfraRequest = utils.formatXml(updateInfraRequest)
273                         execution.setVariable('DELVfModI_updateInfraRequest', updateInfraRequest)
274                         logger.debug('Request for Update Infra Request:\n' + updateInfraRequest)
275
276                         logger.trace('Exited ' + method)
277                 } catch (BpmnError e) {
278                         throw e;
279                 } catch (Exception e) {
280                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
281                                         'Caught exception in ' + method, "BPMN",
282                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
283                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage())
284                 }
285         }
286
287         /**
288          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
289          *
290          * @param execution the execution
291          * @param resultVar the execution variable in which the result will be stored
292          */
293         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
294                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
295                         'execution=' + execution.getId() +
296                         ', resultVar=' + resultVar +
297                         ')'
298                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
299                 logger.trace('Entered ' + method)
300
301                 try {
302                         def request = execution.getVariable("DeleteVfModuleRequest")
303                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
304                         def action = utils.getNodeText(requestInfo, "action")
305
306                         String content =
307                                         """  <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
308                                                    xmlns:ns="http://org.onap/so/request/types/v1"
309                                                    xmlns:ns8="http://org.onap/so/workflow/schema/v1">
310                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
311                         ${requestInfo}
312                         </request-info>
313                         <ns8:status-message>Vf Module has been deleted successfully.</ns8:status-message>
314                         <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name>
315                         </aetgt:MsoCompletionRequest>"""
316
317                         content = utils.formatXml(content)
318                         logger.debug(resultVar + ' = ' + System.lineSeparator() + content)
319                         execution.setVariable(resultVar, content)
320
321                         logger.trace('Exited ' + method)
322                 } catch (BpmnError e) {
323                         throw e;
324                 } catch (Exception e) {
325                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
326                                         'Caught exception in ' + method, "BPMN",
327                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
328                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
329                 }
330         }
331
332         /**
333          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
334          *
335          * @param execution the execution
336          * @param resultVar the execution variable in which the result will be stored
337          */
338         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
339                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
340                         'execution=' + execution.getId() +
341                         ', resultVar=' + resultVar +
342                         ')'
343                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
344                 logger.trace('Entered ' + method)
345
346                 try {
347                         def prefix = execution.getVariable('prefix')
348                         def request = execution.getVariable("DeleteVfModuleRequest")
349                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
350                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
351                         def errorResponseCode = workflowException.getErrorCode()
352                         def errorResponseMsg = workflowException.getErrorMessage()
353                         def encErrorResponseMsg = ""
354                         if (errorResponseMsg != null) {
355                                 encErrorResponseMsg = errorResponseMsg
356                         }
357
358                         String content = """
359                         <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
360                                         xmlns:reqtype="http://org.onap/so/request/types/v1"
361                                         xmlns:msoservtypes="http://org.onap/so/request/types/v1"
362                                         xmlns:structuredtypes="http://org.onap/so/structured/types/v1">
363                                         ${requestInfo}
364                                         <sdncadapterworkflow:WorkflowException>
365                                                 <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage>
366                                                 <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode>
367                                         </sdncadapterworkflow:WorkflowException>
368                                 </sdncadapterworkflow:FalloutHandlerRequest>
369                         """
370                         content = utils.formatXml(content)
371                         logger.debug(resultVar + ' = ' + System.lineSeparator() + content)
372                         execution.setVariable(resultVar, content)
373
374                         logger.trace('Exited ' + method)
375                 } catch (BpmnError e) {
376                         throw e;
377                 } catch (Exception e) {
378                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
379                                         'Caught exception in ' + method, "BPMN",
380                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
381                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
382                 }
383         }
384 }