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