Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / CreateVfModuleInfra.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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 com.att.bpm.scripts;
22
23 import groovy.json.JsonSlurper
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.runtime.Execution
27 import org.apache.commons.lang3.*
28 import org.openecomp.mso.bpmn.core.RollbackData
29 import org.openecomp.mso.bpmn.core.WorkflowException
30
31 public class CreateVfModuleInfra extends AbstractServiceTaskProcessor {
32
33         /**
34          * Validates the request message and sets up the workflow.
35          * @param execution the execution
36          */
37         public void preProcessRequest(Execution execution) {
38                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
39                         'execution=' + execution.getId() +
40                         ')'
41                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
42                 logDebug('Entered ' + method, isDebugLogEnabled)
43
44                 def prefix = 'CVFMI_'
45                 logDebug('Entered 1' + method, isDebugLogEnabled)
46                 execution.setVariable('prefix', prefix)
47                 logDebug('Entered 2' + method, isDebugLogEnabled)
48                 execution.setVariable("isVidRequest", "false")
49
50                 logDebug("Set variables", isDebugLogEnabled)
51
52                 def rollbackData = execution.getVariable("RollbackData")
53                 if (rollbackData == null) {
54                         rollbackData = new RollbackData()
55                 }
56                 execution.setVariable("RollbackData", rollbackData)
57
58                 logDebug("Set rollback data", isDebugLogEnabled)
59                 def incomingRequest = execution.getVariable('bpmnRequest')
60
61                 utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled)
62
63                 // check if request is xml or json
64                 try {
65                         def jsonSlurper = new JsonSlurper()
66                         Map reqMap = jsonSlurper.parseText(incomingRequest)
67                         utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled)
68
69                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
70                         def vnfId = execution.getVariable('vnfId')
71
72                         def vidUtils = new VidUtils(this)
73
74                         String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'CREATE_VF_MODULE', serviceInstanceId)
75
76                         utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled)
77
78                         execution.setVariable(prefix + 'Request', requestInXmlFormat)
79                         execution.setVariable(prefix+'vnfId', vnfId)
80                         execution.setVariable("isVidRequest", "true")
81
82                 }
83                 catch(groovy.json.JsonException je) {
84                         utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled)
85                         workflowException(execution, "Invalid request format", 400)
86
87                 }
88                 catch(Exception e) {
89                         String restFaultMessage = e.getMessage()
90                         //execution.setVariable("CVFMODVOL2_RESTFault", restFaultMessage)
91                         //execution.setVariable("CVFMODVOL2_isDataOk", false)
92                         utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled)
93                         workflowException(execution, restFaultMessage, 400)
94                 }
95
96                 try {
97                         String request = validateInfraRequest(execution)
98
99                         execution.setVariable("CreateVfModuleInfraSuccessIndicator", false)
100                         execution.setVariable("RollbackCompleted", false)
101                         execution.setVariable("DoCreateVfModuleRequest", request)
102                         execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
103                         execution.setVariable("CVFMI_requestInfo",utils.getNodeXml(request,"request-info"))
104                         execution.setVariable("CVFMI_requestId",utils.getNodeText1(request,"request-id"))
105                         execution.setVariable("CVFMI_source",utils.getNodeText1(request,"source"))
106                         execution.setVariable("CVFMI_serviceInstanceId", utils.getNodeText1(request, "service-instance-id"))
107                         execution.setVariable("CVFMI_vnfInputs",utils.getNodeXml(request,"vnf-inputs"))
108                         //backoutOnFailure
109
110                         NetworkUtils networkUtils = new NetworkUtils()
111                         execution.setVariable("CVFMI_rollbackEnabled", networkUtils.isRollbackEnabled(execution,request))
112                         execution.setVariable("CVFMI_originalWorkflowException", null)
113                         def vnfParams = ""
114                         if (utils.nodeExists(request, "vnf-params")) {
115                                 vnfParams = utils.getNodeXml(request,"vnf-params")
116                         }
117                         execution.setVariable("CVFMI_vnfParams", vnfParams)
118
119                         def newVfModuleId = UUID.randomUUID().toString()
120                         execution.setVariable("newVfModuleId", newVfModuleId)
121
122                         logDebug('RequestInfo: ' + execution.getVariable("CVFMI_requestInfo"), isDebugLogEnabled)
123                         logDebug('VnfInputs: ' + execution.getVariable("CVFMI_vnfInputs"), isDebugLogEnabled)
124                         logDebug('VnfParams: ' + execution.getVariable("CVFMI_vnfParams"), isDebugLogEnabled)
125                         logDebug('rollbackEnabled: ' + execution.getVariable("CVFMI_rollbackEnabled"), isDebugLogEnabled)
126
127                         logDebug('Exited ' + method, isDebugLogEnabled)
128                 } catch (BpmnError bpmnError) {
129                         buildErrorResponse(execution,bpmnError.getMessage(),"400")
130                         throw bpmnError
131                 } catch (Exception exception) {
132                         workflowException(execution, exception.getMessage(), 400)
133                 }
134         }
135
136         /**
137          * Validates a workflow response.
138          * @param execution the execution
139          * @param responseVar the execution variable in which the response is stored
140          * @param responseCodeVar the execution variable in which the response code is stored
141          * @param errorResponseVar the execution variable in which the error response is stored
142          */
143         public void validateWorkflowResponse(Execution execution, String responseVar,
144                         String responseCodeVar, String errorResponseVar) {
145                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
146                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
147         }
148
149
150         /**
151          * Sends the empty, synchronous response back to the API Handler.
152          * @param execution the execution
153          */
154         public void sendResponse(Execution execution) {
155                 def method = getClass().getSimpleName() + '.sendResponse(' +
156                         'execution=' + execution.getId() +
157                         ')'
158                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
159                 logDebug('Entered ' + method, isDebugLogEnabled)
160
161                 try {
162                         def requestInfo = execution.getVariable('CVFMI_requestInfo')
163                         def requestId = execution.getVariable('CVFMI_requestId')
164                         def source = execution.getVariable('CVFMI_source')
165                         def progress = getNodeTextForce(requestInfo, 'progress')
166                         if (progress.isEmpty()) {
167                                 progress = '0'
168                         }
169                         def startTime = getNodeTextForce(requestInfo, 'start-time')
170                         if (startTime.isEmpty()) {
171                                 startTime = System.currentTimeMillis()
172                         }
173
174                         // RESTResponse (for API Handler (APIH) Reply Task)
175                         def newVfModuleId = execution.getVariable("newVfModuleId")
176                         String synchResponse = """{"requestReferences":{"instanceId":"${newVfModuleId}","requestId":"${requestId}"}}""".trim()
177
178                         sendWorkflowResponse(execution, 200, synchResponse)
179
180                         logDebug('Exited ' + method, isDebugLogEnabled)
181                 } catch (BpmnError e) {
182                         throw e;
183                 } catch (Exception e) {
184                         logError('Caught exception in ' + method, e)
185                         createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
186                 }
187         }
188
189         /**
190          *
191          * @param execution the execution
192          */
193         public void postProcessResponse(Execution execution){
194                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
195
196                 utils.log("DEBUG", " ======== STARTED PostProcessResponse Process ======== ", isDebugEnabled)
197                 try{
198                         def request = execution.getVariable("DoCreateVfModuleRequest")
199                         def requestInfo = utils.getNodeXml(request, 'request-info', false)
200                         def action = utils.getNodeText1(requestInfo, "action")
201
202                         utils.log("DEBUG", "requestInfo is: " + requestInfo, isDebugEnabled)
203                         utils.log("DEBUG", "action is: " + action, isDebugEnabled)
204
205                         String payload =
206                                         """  <aetgt:MsoCompletionRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
207                                xmlns:ns="http://ecomp.att.com/mso/request/types/v1"
208                                xmlns:ns8="http://ecomp.att.com/mso/workflow/schema/v1">
209                         <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
210                         ${requestInfo}
211                         </request-info>
212                         <ns8:status-message>Vf Module has been created successfully.</ns8:status-message>
213                         <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name>
214                         </aetgt:MsoCompletionRequest>"""
215
216                         payload = utils.formatXml(payload)
217                         execution.setVariable("CVFMI_SuccessFlag", true)
218                         execution.setVariable("CVFMI_msoCompletionRequest", payload)
219                         utils.log("DEBUG", "Outgoing MsoCompletionRequest: \n" + payload, isDebugEnabled)
220
221                 }catch(Exception e){
222                         utils.log("ERROR", "Exception Occured Processing PostProcessResponse. Exception is:\n" + e, isDebugEnabled)
223                         execution.setVariable("CVFMI_ErrorResponse", "Error Occured during PostProcessResponse Method:\n" + e.getMessage())
224                 }
225                 utils.log("DEBUG", "======== COMPLETED PostProcessResponse Process ======== ", isDebugEnabled)
226         }
227
228
229
230
231
232         /**
233          * Validates the request, request id and service instance id.  If a problem is found,
234          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
235          * method also sets up the log context for the workflow.
236          * @param execution the execution
237          * @return the validated request
238          */
239         public String validateInfraRequest(Execution execution) {
240                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
241                         'execution=' + execution.getId() +
242                         ')'
243                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
244                 logDebug('Entered ' + method, isDebugLogEnabled)
245
246                 String processKey = getProcessKey(execution);
247                 def prefix = execution.getVariable("prefix")
248
249                 if (prefix == null) {
250                         createWorkflowException(execution, 1002, processKey + " prefix is null")
251                 }
252
253                 try {
254                         def request = execution.getVariable(prefix + 'Request')
255
256                         if (request == null) {
257                                 request = execution.getVariable(processKey + 'Request')
258
259                                 if (request == null) {
260                                         request = execution.getVariable('bpmnRequest')
261                                 }
262
263                                 setVariable(execution, processKey + 'Request', null);
264                                 setVariable(execution, 'bpmnRequest', null);
265                                 setVariable(execution, prefix + 'Request', request);
266                         }
267
268                         if (request == null) {
269                                 createWorkflowException(execution, 1002, processKey + " request is null")
270                         }
271
272                         /*
273
274                         def requestId = execution.getVariable("att-mso-request-id")
275
276                         if (requestId == null) {
277                                 createWorkflowException(execution, 1002, processKey + " request has no att-mso-request-id")
278                         }
279
280                         setVariable(execution, prefix + 'requestId', requestId)
281
282                         def serviceInstanceId = execution.getVariable("att-mso-service-instance-id")
283
284                         if (serviceInstanceId == null) {
285                                 createWorkflowException(execution, 1002, processKey + " request message has no att-mso-service-instance-id")
286                         }
287
288                         utils.logContext(requestId, serviceInstanceId)
289                         */
290                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
291                         logDebug('Exited ' + method, isDebugLogEnabled)
292                         return request
293                 } catch (BpmnError e) {
294                         throw e;
295                 } catch (Exception e) {
296                         logError('Caught exception in ' + method, e)
297                         createWorkflowException(execution, 1002, "Invalid Message")
298                 }
299         }
300
301         public void prepareUpdateInfraRequest(Execution execution){
302                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
303
304                 utils.log("DEBUG", " ======== STARTED prepareUpdateInfraRequest Process ======== ", isDebugEnabled)
305                 try{
306
307                         String vnfInputs = execution.getVariable("CVFMI_vnfInputs")
308                         String requestInfo = execution.getVariable("CVFMI_requestInfo")
309                         def aicCloudRegion      = utils.getNodeText1(vnfInputs, "aic-cloud-region")
310                         def tenantId = utils.getNodeText1(vnfInputs, "tenant-id")
311                         def requestId = utils.getNodeText1(requestInfo, "request-id")
312                         def vnfId = execution.getVariable("CVFMI_vnfId")
313                         def vfModuleId = execution.getVariable("CVFMI_vfModuleId")
314
315                         def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_db_endpoint")
316                         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
317                         utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled)
318
319                         String payload =
320                                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
321                                                 xmlns:ns="http://com.att.mso/requestsdb">
322                                                 <soapenv:Header/>
323                                                 <soapenv:Body>
324                                                         <ns:updateInfraRequest xmlns:ns="http://com.att.mso/requestsdb">
325                                                         <requestId>${requestId}</requestId>
326                                                         <lastModifiedBy>BPMN</lastModifiedBy>
327                                                         <statusMessage>VF Module successfully created</statusMessage>
328                                                         <responseBody></responseBody>
329                                                         <requestStatus>COMPLETE</requestStatus>
330                                                         <progress>100</progress>
331                                                         <vnfOutputs>&lt;vnf-outputs xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1" xmlns:aetgt="http://ecomp.att.com/mso/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"&gt;&lt;vnf-id&gt;${vnfId}&lt;/vnf-id&gt;&lt;vf-module-id&gt;${vfModuleId}&lt;/vf-module-id&gt;&lt;/vnf-outputs&gt;</vnfOutputs>
332                                                         <vfModuleId>${vfModuleId}</vfModuleId>
333                                                 </ns:updateInfraRequest>
334                                         </soapenv:Body>
335                                 </soapenv:Envelope>"""
336
337                         payload = utils.formatXml(payload)
338                         execution.setVariable("CVFMI_updateInfraRequest", payload)
339                         utils.log("DEBUG", "Outgoing UpdateInfraRequest: \n" + payload, isDebugEnabled)
340
341
342                 }catch(Exception e){
343                         utils.log("ERROR", "Exception Occured Processing prepareUpdateInfraRequest. Exception is:\n" + e, isDebugEnabled)
344                         execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateInfraRequest Method:\n" + e.getMessage())
345                 }
346                 utils.log("DEBUG", "======== COMPLETED prepareUpdateInfraRequest Process ======== ", isDebugEnabled)
347         }
348
349         /**
350          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
351          *
352          * @param execution the execution
353          * @param resultVar the execution variable in which the result will be stored
354          */
355         public void falloutHandlerPrep(Execution execution, String resultVar) {
356                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
357                         'execution=' + execution.getId() +
358                         ', resultVar=' + resultVar +
359                         ')'
360                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
361                 logDebug('Entered ' + method, isDebugLogEnabled)
362
363
364                 try {
365                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
366                         def request = execution.getVariable("DoCreateVfModuleRequest")
367                         def requestInformation = utils.getNodeXml(request, 'request-info', false)
368                         def errorResponseCode = workflowException.getErrorCode()
369                         def errorResponseMsg = workflowException.getErrorMessage()
370                         def encErrorResponseMsg = ""
371                         if (errorResponseMsg != null) {
372                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
373                         }
374
375                         String content = """
376                                 <aetgt:FalloutHandlerRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
377                                                 xmlns:reqtype="http://ecomp.att.com/mso/request/types/v1"
378                                                 xmlns:msoservtypes="http://ecomp.att.com/mso/request/types/v1"
379                                                 xmlns:structuredtypes="http://ecomp.att.com/mso/structured/types/v1">
380                                                 ${requestInformation}
381                                         <aetgt:WorkflowException>
382                                                 <aetgt:ErrorMessage>${encErrorResponseMsg}</aetgt:ErrorMessage>
383                                                 <aetgt:ErrorCode>${errorResponseCode}</aetgt:ErrorCode>
384                                         </aetgt:WorkflowException>
385                                 </aetgt:FalloutHandlerRequest>
386                         """
387
388                         logDebug("CONTENT before translation: " + content, isDebugLogEnabled)
389                         content = utils.formatXml(content)
390                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
391                         execution.setVariable(resultVar, content)
392
393                         logDebug('Exited ' + method, isDebugLogEnabled)
394                 } catch (BpmnError e) {
395                         throw e;
396                 } catch (Exception e) {
397                         logError('Caught exception in ' + method, e)
398                         createWorkflowException(execution, 2000, 'Internal Error')
399                 }
400         }
401
402         public void logAndSaveOriginalException(Execution execution) {
403                 def method = getClass().getSimpleName() + '.validateRollbackResponse(' +
404                         'execution=' + execution.getId() +
405                         ')'
406                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
407                 logDebug('Entered ' + method, isDebugLogEnabled)
408
409                 logWorkflowException(execution, 'CreateVfModuleInfra caught an event')
410                 saveWorkflowException(execution, 'CVFMI_originalWorkflowException')
411         }
412
413         public void validateRollbackResponse(Execution execution) {
414                 def method = getClass().getSimpleName() + '.validateRollbackResponse(' +
415                         'execution=' + execution.getId() +
416                         ')'
417                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
418                 logDebug('Entered ' + method, isDebugLogEnabled)
419
420                 def originalException = execution.getVariable("CVFMI_originalWorkflowException")
421                 execution.setVariable("WorkflowException", originalException)
422
423                 execution.setVariable("RollbackCompleted", true)
424
425         }
426
427
428 }