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