7389ff0916ea8106ea9e6d351504a170cc2f236f
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / UpdateVfModuleInfra.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 org.openecomp.mso.bpmn.infrastructure.scripts
22
23 import groovy.json.JsonOutput
24 import groovy.json.JsonSlurper
25 import groovy.util.Node
26 import groovy.util.XmlParser;
27 import groovy.xml.QName
28
29 import java.io.Serializable;
30 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.runtime.Execution
33 import org.openecomp.mso.rest.APIResponse
34 import org.openecomp.mso.rest.RESTClient
35 import org.openecomp.mso.rest.RESTConfig
36 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
37 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
38 import org.openecomp.mso.bpmn.core.RollbackData
39 import org.openecomp.mso.bpmn.core.WorkflowException
40
41
42 public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor {
43
44         ExceptionUtil exceptionUtil = new ExceptionUtil()
45
46         /**
47          * Initialize the flow's variables.
48          *
49          * @param execution The flow's execution instance.
50          */
51         public void initProcessVariables(Execution execution) {
52                 execution.setVariable('prefix', 'UPDVfModI_')
53                 execution.setVariable('UPDVfModI_Request', null)
54                 execution.setVariable('UPDVfModI_requestInfo', null)
55                 execution.setVariable('UPDVfModI_requestId', null)
56                 execution.setVariable('UPDVfModI_source', null)
57                 execution.setVariable('UPDVfModI_vnfInputs', null)
58                 execution.setVariable('UPDVfModI_vnfId', null)
59                 execution.setVariable('UPDVfModI_vfModuleId', null)
60                 execution.setVariable('UPDVfModI_tenantId', null)
61                 execution.setVariable('UPDVfModI_volumeGroupId', null)
62                 execution.setVariable('UPDVfModI_vnfParams', null)
63                 execution.setVariable('UPDVfModI_updateInfraRequest', null)
64                 execution.setVariable('UpdateVfModuleSuccessIndicator', false)
65         }
66
67         /**
68          * Check for missing elements in the received request.
69          *
70          * @param execution The flow's execution instance.
71          */
72         public void preProcessRequest(Execution execution) {
73                 
74                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
75                 'execution=' + execution.getId() +
76                 ')'
77                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
78                 logDebug('Entered ' + method, isDebugLogEnabled)
79
80                 initProcessVariables(execution)
81
82                 def prefix = "UPDVfModI_"               
83
84                 def incomingRequest = execution.getVariable('bpmnRequest')
85
86                 utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled)
87                 try {
88                         def jsonSlurper = new JsonSlurper()
89                         def jsonOutput = new JsonOutput()
90                         Map reqMap = jsonSlurper.parseText(incomingRequest)
91                         utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled)
92
93                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
94                         def vnfId = execution.getVariable('vnfId')
95                         
96                         execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId)
97                         execution.setVariable(prefix+'vnfId', vnfId)
98                         execution.setVariable("isVidRequest", "true")
99                         
100                         def vnfName = ''
101                         def asdcServiceModelVersion = ''
102                         def serviceModelInfo = null
103                         def vnfModelInfo = null
104                         
105                         def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList
106                                                 
107                         if (relatedInstanceList != null) {
108                                 relatedInstanceList.each {
109                                         if (it.relatedInstance.modelInfo?.modelType == 'service') {
110                                                 asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
111                                                 serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
112                                                 
113                                         }
114                                         if (it.relatedInstance.modelInfo.modelType == 'vnf') {
115                                                 vnfName = it.relatedInstance.instanceName ?: ''
116                                                 vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
117                                         }
118                                 }
119                         }
120                         
121                         execution.setVariable(prefix + 'vnfName', vnfName)
122                         execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion)
123                         execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo)
124                         execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo)                    
125                         
126                         def vnfType = execution.getVariable('vnfType')
127                         execution.setVariable(prefix + 'vnfType', vnfType)      
128                         def vfModuleId = execution.getVariable('vfModuleId')
129                         execution.setVariable(prefix + 'vfModuleId', vfModuleId)
130                         def volumeGroupId = execution.getVariable('volumeGroupId')
131                         execution.setVariable(prefix + 'volumeGroupId', volumeGroupId)
132                         def userParams = reqMap.requestDetails?.requestParameters?.userParams                                   
133                         
134                         Map<String, String> userParamsMap = [:]
135                         if (userParams != null) {
136                                 userParams.each { userParam ->
137                                         userParamsMap.put(userParam.name, userParam.value)
138                                 }                                                       
139                         }               
140                                                 
141                         utils.log("DEBUG", 'Processed user params: ' + userParamsMap, isDebugLogEnabled)                
142                         
143                         execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap)
144                         
145                         def isBaseVfModule = "false"
146                         if (execution.getVariable('isBaseVfModule') == true) {
147                                 isBaseVfModule = "true"
148                         }                       
149                         
150                         execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule)
151                                                 
152                         def requestId = execution.getVariable("mso-request-id")
153                         execution.setVariable(prefix + 'requestId', requestId)
154                         
155                         def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo)
156                         execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo)
157                         
158                         def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback
159                         
160                         
161                         def backoutOnFailure = ""
162                         if(suppressRollback != null){
163                                 if ( suppressRollback == true) {
164                                         backoutOnFailure = "false"
165                                 } else if ( suppressRollback == false) {
166                                         backoutOnFailure = "true"
167                                 }
168                         }
169                         
170                         execution.setVariable('disableRollback', suppressRollback)
171                         
172                         def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null
173                         execution.setVariable(prefix + 'vfModuleName', vfModuleName)
174                         
175                         def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: ''
176                         execution.setVariable(prefix + 'serviceId', serviceId)
177                         
178                         def usePreload = reqMap.requestDetails?.requestParameters?.usePreload
179                         execution.setVariable(prefix + 'usePreload', usePreload)
180                         
181                         def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration
182                         def lcpCloudRegionId    = cloudConfiguration.lcpCloudRegionId
183                         execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId)
184                         def tenantId = cloudConfiguration.tenantId
185                         execution.setVariable(prefix + 'tenantId', tenantId)
186                         
187                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
188                         execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId)
189                         
190                         execution.setVariable(prefix + 'sdncVersion', '1702')
191
192                         execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false)
193                                                 
194                         execution.setVariable("isDebugLogEnabled", isDebugLogEnabled)
195                         
196                         
197                         def source = reqMap.requestDetails?.requestInfo?.source
198                         execution.setVariable(prefix + "source", source)
199                         
200                         //For Completion Handler & Fallout Handler
201                         String requestInfo =
202                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
203                                         <request-id>${requestId}</request-id>
204                                         <action>UPDATE</action>
205                                         <source>${source}</source>
206                                    </request-info>"""
207                         
208                         execution.setVariable(prefix + "requestInfo", requestInfo)
209                         
210                         //backoutOnFailure                      
211
212                         logDebug('RequestInfo: ' + execution.getVariable(prefix + "requestInfo"), isDebugLogEnabled)                    
213                                                 
214                         logDebug('Exited ' + method, isDebugLogEnabled)
215
216                 }
217                 catch(groovy.json.JsonException je) {
218                         utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled)
219                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
220
221                 }
222                 catch(Exception e) {
223                         String restFaultMessage = e.getMessage()
224                         utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled)
225                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
226                 }       
227         }
228
229         /**
230          * Prepare and send the sychronous response for this flow.
231          *
232          * @param execution The flow's execution instance.
233          */
234         public void sendSynchResponse(Execution execution) {
235                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
236                         'execution=' + execution.getId() +
237                         ')'
238                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
239                 logDebug('Entered ' + method, isDebugLogEnabled)
240
241
242                 try {
243                         def requestInfo = execution.getVariable('UPDVfModI_requestInfo')
244                         def requestId = execution.getVariable('UPDVfModI_requestId')
245                         def source = execution.getVariable('UPDVfModI_source')
246                         def progress = getNodeTextForce(requestInfo, 'progress')
247                         if (progress.isEmpty()) {
248                                 progress = '0'
249                         }
250                         def startTime = getNodeTextForce(requestInfo, 'start-time')
251                         if (startTime.isEmpty()) {
252                                 startTime = System.currentTimeMillis()
253                         }
254
255                         // RESTResponse (for API Handler (APIH) Reply Task)
256                         def vfModuleId = execution.getVariable("vfModuleId")
257                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
258
259                         sendWorkflowResponse(execution, 200, synchResponse)
260
261                         logDebug('Exited ' + method, isDebugLogEnabled)
262                 } catch (BpmnError e) {
263                         throw e;
264                 } catch (Exception e) {
265                         logError('Caught exception in ' + method, e)
266                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
267                 }
268         }
269
270         /**
271          * Prepare the Request for invoking the DoUpdateVfModule subflow.
272          *
273          * NOTE: Currently, the method just logs passing through as the
274          * incoming Request to this main flow is used as the Request to
275          * the DoUpdateVfModule subflow. No preparation processing is
276          * necessary.
277          *
278          * @param execution The flow's execution instance.
279          */
280         public void prepDoUpdateVfModule(Execution execution) {
281                 def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' +
282                         'execution=' + execution.getId() +
283                         ')'
284                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
285                 logDebug('Entered ' + method, isDebugLogEnabled)
286
287                 try {
288
289                         logDebug('Exited ' + method, isDebugLogEnabled)
290                 } catch (BpmnError e) {
291                         throw e;
292                 } catch (Exception e) {
293                         logError('Caught exception in ' + method, e)
294                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage())
295                 }
296         }
297
298         /**
299          * Prepare the Request for updating the DB for this Infra Request.
300          *
301          * @param execution The flow's execution instance.
302          */
303         public void prepUpdateInfraRequest(Execution execution) {
304                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
305                         'execution=' + execution.getId() +
306                         ')'
307                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
308                 logDebug('Entered ' + method, isDebugLogEnabled)
309
310                 try {
311                         def requestId = execution.getVariable('UPDVfModI_requestId')
312                         def vnfId = execution.getVariable('UPDVfModI_vnfId')
313                         def vfModuleId = execution.getVariable('UPDVfModI_vfModuleId')
314                         def tenantId = execution.getVariable('UPDVfModI_tenantId')
315                         def volumeGroupId = execution.getVariable('UPDVfModI_volumeGroupId')
316
317                         String updateInfraRequest = """
318                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
319                                                 xmlns:req="http://org.openecomp.mso/requestsdb">
320                                         <soapenv:Header/>
321                                         <soapenv:Body>
322                                                 <req:updateInfraRequest>
323                                                         <requestId>${requestId}</requestId>
324                                                         <lastModifiedBy>BPEL</lastModifiedBy>
325                                                         <requestStatus>COMPLETE</requestStatus>
326                                                         <progress>100</progress>
327                                                         <vnfOutputs>
328                                                                 <vnf-id>${vnfId}</vnf-id>
329                                                                 <vf-module-id>${vfModuleId}</vf-module-id>
330                                                                 <tenant-id>${tenantId}</tenant-id>
331                                                                 <volume-group-id>${volumeGroupId}</volume-group-id>
332                                                         </vnfOutputs>
333                                                 </req:updateInfraRequest>
334                                         </soapenv:Body>
335                                 </soapenv:Envelope>
336                         """
337
338                         updateInfraRequest = utils.formatXml(updateInfraRequest)
339                         execution.setVariable('UPDVfModI_updateInfraRequest', updateInfraRequest)
340                         logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled)
341
342                         logDebug('Exited ' + method, isDebugLogEnabled)
343                 } catch (BpmnError e) {
344                         throw e;
345                 } catch (Exception e) {
346                         logError('Caught exception in ' + method, e)
347                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage())
348                 }
349         }
350
351         /**
352          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
353          *
354          * @param execution the execution
355          * @param resultVar the execution variable in which the result will be stored
356          */
357         public void completionHandlerPrep(Execution execution, String resultVar) {
358                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
359                         'execution=' + execution.getId() +
360                         ', resultVar=' + resultVar +
361                         ')'
362                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
363                 logDebug('Entered ' + method, isDebugLogEnabled)
364
365                 try {
366                         def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo')
367
368                         String content = """
369                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
370                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1">
371                                         ${requestInfo}
372                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
373                                 </sdncadapterworkflow:MsoCompletionRequest>
374                         """
375
376                         content = utils.formatXml(content)
377                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
378                         execution.setVariable(resultVar, content)
379
380                         logDebug('Exited ' + method, isDebugLogEnabled)
381                 } catch (BpmnError e) {
382                         throw e;
383                 } catch (Exception e) {
384                         logError('Caught exception in ' + method, e)
385                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
386                 }
387         }
388
389         /**
390          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
391          *
392          * @param execution the execution
393          * @param resultVar the execution variable in which the result will be stored
394          */
395         public void falloutHandlerPrep(Execution execution, String resultVar) {
396                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
397                         'execution=' + execution.getId() +
398                         ', resultVar=' + resultVar +
399                         ')'
400                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
401                 logDebug('Entered ' + method, isDebugLogEnabled)
402
403                 try {
404                         def prefix = execution.getVariable('prefix')
405                         def request = getVariable(execution, prefix+'Request')
406                         def requestInformation = execution.getVariable(prefix + "requestInfo")
407
408                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
409                         def errorResponseCode = workflowException.getErrorCode()
410                         def errorResponseMsg = workflowException.getErrorMessage()
411                         def encErrorResponseMsg = ""
412                         if (errorResponseMsg != null) {
413                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
414                         }
415
416                         String content = """
417                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
418                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1"
419                                                 xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1"
420                                                 xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1">
421                                         ${requestInformation}
422                                         <sdncadapterworkflow:WorkflowException>
423                                                 <sdncadapterworkflow:ErrorMessage>${encErrorResponseMsg}</sdncadapterworkflow:ErrorMessage>
424                                                 <sdncadapterworkflow:ErrorCode>${errorResponseCode}</sdncadapterworkflow:ErrorCode>
425                                         </sdncadapterworkflow:WorkflowException>
426                                 </sdncadapterworkflow:FalloutHandlerRequest>
427                         """
428                         content = utils.formatXml(content)
429                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
430                         execution.setVariable(resultVar, content)
431
432                         logDebug('Exited ' + method, isDebugLogEnabled)
433                 } catch (BpmnError e) {
434                         throw e;
435                 } catch (Exception e) {
436                         logError('Caught exception in ' + method, e)
437                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
438                 }
439         }
440
441         /**
442          * Validates the request, request id and service instance id.  If a problem is found,
443          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
444          * method also sets up the log context for the workflow.
445          * @param execution the execution
446          * @return the validated request
447          */
448         public String validateInfraRequest(Execution execution) {
449                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
450                         'execution=' + execution.getId() +
451                         ')'
452                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
453                 logDebug('Entered ' + method, isDebugLogEnabled)
454
455                 String processKey = getProcessKey(execution);
456                 def prefix = execution.getVariable("prefix")
457
458                 if (prefix == null) {
459                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
460                 }
461
462                 try {
463                         def request = execution.getVariable(prefix + 'Request')
464
465                         if (request == null) {
466                                 request = execution.getVariable(processKey + 'Request')
467
468                                 if (request == null) {
469                                         request = execution.getVariable('bpmnRequest')
470                                 }
471
472                                 setVariable(execution, processKey + 'Request', null);
473                                 setVariable(execution, 'bpmnRequest', null);
474                                 setVariable(execution, prefix + 'Request', request);
475                         }
476
477                         if (request == null) {
478                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
479                         }
480
481                         /*
482
483                         def requestId = execution.getVariable("mso-request-id")
484
485                         if (requestId == null) {
486                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
487                         }
488
489                         setVariable(execution, prefix + 'requestId', requestId)
490
491                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
492
493                         if (serviceInstanceId == null) {
494                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
495                         }
496
497                         utils.logContext(requestId, serviceInstanceId)
498                         */
499                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
500                         logDebug('Exited ' + method, isDebugLogEnabled)
501                         return request
502                 } catch (BpmnError e) {
503                         throw e;
504                 } catch (Exception e) {
505                         logError('Caught exception in ' + method, e)
506                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
507                 }
508         }
509
510 }