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