357ce69d502909b4277a33dd0a53542c95a29292
[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.getServiceName(), 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", MsoLogger.getServiceName(),
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", MsoLogger.getServiceName(),
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 ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
233                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage())
234                 }
235         }
236
237         /**
238          * Prepare the DB update to add an entry for the Vf Module request.
239          *
240          * @param execution The flow's execution instance.
241          */
242         public void prepUpdateInfraRequest(DelegateExecution execution) {
243                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
244                         'execution=' + execution.getId() +
245                         ')'
246                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
247                 logger.trace('Entered ' + method)
248
249                 try {
250                         def requestId = execution.getVariable('DELVfModI_requestId')
251                         def vnfId = execution.getVariable('DELVfModI_vnfId')
252                         def vfModuleId = execution.getVariable('DELVfModI_vfModuleId')
253                         def tenantId = execution.getVariable('DELVfModI_tenantId')
254                         def volumeGroupId = execution.getVariable('DELVfModI_volumeGroupId')
255
256                         String updateInfraRequest = """
257                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
258                                         xmlns:req="http://org.onap.so/requestsdb">
259                                         <soapenv:Header/>
260                                         <soapenv:Body>
261                                                 <req:updateInfraRequest>
262                                                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
263                                                         <lastModifiedBy>BPMN</lastModifiedBy>
264                                                         <requestStatus>COMPLETED</requestStatus>
265                                                         <progress>100</progress>
266                                                 </req:updateInfraRequest>
267                                         </soapenv:Body>
268                                 </soapenv:Envelope>
269                         """
270
271                         updateInfraRequest = utils.formatXml(updateInfraRequest)
272                         execution.setVariable('DELVfModI_updateInfraRequest', updateInfraRequest)
273                         logger.debug('Request for Update Infra Request:\n' + updateInfraRequest)
274
275                         logger.trace('Exited ' + method)
276                 } catch (BpmnError e) {
277                         throw e;
278                 } catch (Exception e) {
279                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
280                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
281                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
282                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage())
283                 }
284         }
285
286         /**
287          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
288          *
289          * @param execution the execution
290          * @param resultVar the execution variable in which the result will be stored
291          */
292         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
293                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
294                         'execution=' + execution.getId() +
295                         ', resultVar=' + resultVar +
296                         ')'
297                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
298                 logger.trace('Entered ' + method)
299
300                 try {
301                         def request = execution.getVariable("DeleteVfModuleRequest")
302                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
303                         def action = utils.getNodeText(requestInfo, "action")
304
305                         String content =
306                                         """  <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
307                                                    xmlns:ns="http://org.onap/so/request/types/v1"
308                                                    xmlns:ns8="http://org.onap/so/workflow/schema/v1">
309                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
310                         ${requestInfo}
311                         </request-info>
312                         <ns8:status-message>Vf Module has been deleted successfully.</ns8:status-message>
313                         <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name>
314                         </aetgt:MsoCompletionRequest>"""
315
316                         content = utils.formatXml(content)
317                         logger.debug(resultVar + ' = ' + System.lineSeparator() + content)
318                         execution.setVariable(resultVar, content)
319
320                         logger.trace('Exited ' + method)
321                 } catch (BpmnError e) {
322                         throw e;
323                 } catch (Exception e) {
324                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
325                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
326                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
327                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
328                 }
329         }
330
331         /**
332          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
333          *
334          * @param execution the execution
335          * @param resultVar the execution variable in which the result will be stored
336          */
337         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
338                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
339                         'execution=' + execution.getId() +
340                         ', resultVar=' + resultVar +
341                         ')'
342                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
343                 logger.trace('Entered ' + method)
344
345                 try {
346                         def prefix = execution.getVariable('prefix')
347                         def request = execution.getVariable("DeleteVfModuleRequest")
348                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
349                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
350                         def errorResponseCode = workflowException.getErrorCode()
351                         def errorResponseMsg = workflowException.getErrorMessage()
352                         def encErrorResponseMsg = ""
353                         if (errorResponseMsg != null) {
354                                 encErrorResponseMsg = errorResponseMsg
355                         }
356
357                         String content = """
358                         <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
359                                         xmlns:reqtype="http://org.onap/so/request/types/v1"
360                                         xmlns:msoservtypes="http://org.onap/so/request/types/v1"
361                                         xmlns:structuredtypes="http://org.onap/so/structured/types/v1">
362                                         ${requestInfo}
363                                         <sdncadapterworkflow:WorkflowException>
364                                                 <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage>
365                                                 <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode>
366                                         </sdncadapterworkflow:WorkflowException>
367                                 </sdncadapterworkflow:FalloutHandlerRequest>
368                         """
369                         content = utils.formatXml(content)
370                         logger.debug(resultVar + ' = ' + System.lineSeparator() + content)
371                         execution.setVariable(resultVar, content)
372
373                         logger.trace('Exited ' + method)
374                 } catch (BpmnError e) {
375                         throw e;
376                 } catch (Exception e) {
377                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
378                                         'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),
379                                         MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
380                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
381                 }
382         }
383 }