Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / 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                         def tenantId = cloudConfiguration.tenantId
179                         execution.setVariable(prefix + 'tenantId', tenantId)
180                         
181                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
182                         execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId)
183                         
184                         execution.setVariable(prefix + 'sdncVersion', '1702')
185
186                         execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false)
187                                                 
188
189                         
190                         
191                         def source = reqMap.requestDetails?.requestInfo?.source
192                         execution.setVariable(prefix + "source", source)
193                         
194                         //For Completion Handler & Fallout Handler
195                         String requestInfo =
196                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
197                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
198                                         <action>UPDATE</action>
199                                         <source>${MsoUtils.xmlEscape(source)}</source>
200                                    </request-info>"""
201                         
202                         execution.setVariable(prefix + "requestInfo", requestInfo)
203                         
204                         //backoutOnFailure                      
205
206                         msoLogger.debug('RequestInfo: ' + execution.getVariable(prefix + "requestInfo"))                        
207                                                 
208                         msoLogger.trace('Exited ' + method)
209
210                 }
211                 catch(groovy.json.JsonException je) {
212                         msoLogger.debug(" Request is not in JSON format.")
213                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
214
215                 }
216                 catch(Exception e) {
217                         String restFaultMessage = e.getMessage()
218                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
219                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
220                 }       
221         }
222
223         /**
224          * Prepare and send the sychronous response for this flow.
225          *
226          * @param execution The flow's execution instance.
227          */
228         public void sendSynchResponse(DelegateExecution execution) {
229                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
230                         'execution=' + execution.getId() +
231                         ')'
232
233                 msoLogger.trace('Entered ' + method)
234
235
236                 try {
237                         def requestInfo = execution.getVariable('UPDVfModI_requestInfo')
238                         def requestId = execution.getVariable('UPDVfModI_requestId')
239                         def source = execution.getVariable('UPDVfModI_source')
240                         def progress = getNodeTextForce(requestInfo, 'progress')
241                         if (progress.isEmpty()) {
242                                 progress = '0'
243                         }
244                         def startTime = getNodeTextForce(requestInfo, 'start-time')
245                         if (startTime.isEmpty()) {
246                                 startTime = System.currentTimeMillis()
247                         }
248
249                         // RESTResponse (for API Handler (APIH) Reply Task)
250                         def vfModuleId = execution.getVariable("vfModuleId")
251                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
252
253                         sendWorkflowResponse(execution, 200, synchResponse)
254
255                         msoLogger.trace('Exited ' + method)
256                 } catch (BpmnError e) {
257                         throw e;
258                 } catch (Exception e) {
259                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
260                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
261                 }
262         }
263
264         /**
265          * Prepare the Request for invoking the DoUpdateVfModule subflow.
266          *
267          * NOTE: Currently, the method just logs passing through as the
268          * incoming Request to this main flow is used as the Request to
269          * the DoUpdateVfModule subflow. No preparation processing is
270          * necessary.
271          *
272          * @param execution The flow's execution instance.
273          */
274         public void prepDoUpdateVfModule(DelegateExecution execution) {
275                 def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' +
276                         'execution=' + execution.getId() +
277                         ')'
278
279                 msoLogger.trace('Entered ' + method)
280
281                 try {
282
283                         msoLogger.trace('Exited ' + method)
284                 } catch (BpmnError e) {
285                         throw e;
286                 } catch (Exception e) {
287                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
288                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage())
289                 }
290         }
291
292         /**
293          * Prepare the Request for updating the DB for this Infra Request.
294          *
295          * @param execution The flow's execution instance.
296          */
297         public void prepUpdateInfraRequest(DelegateExecution execution) {
298                 def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' +
299                         'execution=' + execution.getId() +
300                         ')'
301
302                 msoLogger.trace('Entered ' + method)
303
304                 try {
305                         def requestId = execution.getVariable('UPDVfModI_requestId')
306                         def vnfId = execution.getVariable('UPDVfModI_vnfId')
307                         def vfModuleId = execution.getVariable('UPDVfModI_vfModuleId')
308                         def tenantId = execution.getVariable('UPDVfModI_tenantId')
309                         def volumeGroupId = execution.getVariable('UPDVfModI_volumeGroupId')
310
311                         String updateInfraRequest = """
312                                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
313                                                 xmlns:req="http://org.onap.so/requestsdb">
314                                         <soapenv:Header/>
315                                         <soapenv:Body>
316                                                 <req:updateInfraRequest>
317                                                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
318                                                         <lastModifiedBy>BPEL</lastModifiedBy>
319                                                         <requestStatus>COMPLETE</requestStatus>
320                                                         <progress>100</progress>
321                                                         <vnfOutputs>
322                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
323                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
324                                                                 <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id>
325                                                                 <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id>
326                                                         </vnfOutputs>
327                                                 </req:updateInfraRequest>
328                                         </soapenv:Body>
329                                 </soapenv:Envelope>
330                         """
331
332                         updateInfraRequest = utils.formatXml(updateInfraRequest)
333                         execution.setVariable('UPDVfModI_updateInfraRequest', updateInfraRequest)
334                         msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest)
335
336                         msoLogger.trace('Exited ' + method)
337                 } catch (BpmnError e) {
338                         throw e;
339                 } catch (Exception e) {
340                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
341                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage())
342                 }
343         }
344
345         /**
346          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
347          *
348          * @param execution the execution
349          * @param resultVar the execution variable in which the result will be stored
350          */
351         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
352                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
353                         'execution=' + execution.getId() +
354                         ', resultVar=' + resultVar +
355                         ')'
356
357                 msoLogger.trace('Entered ' + method)
358
359                 try {
360                         def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo')
361
362                         String content = """
363                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
364                                                 xmlns:reqtype="http://org.onap/so/request/types/v1">
365                                         ${requestInfo}
366                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
367                                 </sdncadapterworkflow:MsoCompletionRequest>
368                         """
369
370                         content = utils.formatXml(content)
371                         msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content)
372                         execution.setVariable(resultVar, content)
373
374                         msoLogger.trace('Exited ' + method)
375                 } catch (BpmnError e) {
376                         throw e;
377                 } catch (Exception e) {
378                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
379                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
380                 }
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(DelegateExecution execution, String resultVar) {
390                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
391                         'execution=' + execution.getId() +
392                         ', resultVar=' + resultVar +
393                         ')'
394
395                 msoLogger.trace('Entered ' + method)
396
397                 try {
398                         def prefix = execution.getVariable('prefix')
399                         def request = getVariable(execution, prefix+'Request')
400                         def requestInformation = execution.getVariable(prefix + "requestInfo")
401
402                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
403                         def errorResponseCode = workflowException.getErrorCode()
404                         def errorResponseMsg = workflowException.getErrorMessage()
405                         def encErrorResponseMsg = ""
406                         if (errorResponseMsg != null) {
407                                 encErrorResponseMsg = errorResponseMsg
408                         }
409
410                         String content = """
411                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
412                                                 xmlns:reqtype="http://org.onap/so/request/types/v1"
413                                                 xmlns:msoservtypes="http://org.onap/so/request/types/v1"
414                                                 xmlns:structuredtypes="http://org.onap/so/structured/types/v1">
415                                         ${requestInformation}
416                                         <sdncadapterworkflow:WorkflowException>
417                                                 <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage>
418                                                 <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode>
419                                         </sdncadapterworkflow:WorkflowException>
420                                 </sdncadapterworkflow:FalloutHandlerRequest>
421                         """
422                         content = utils.formatXml(content)
423                         msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content)
424                         execution.setVariable(resultVar, content)
425
426                         msoLogger.trace('Exited ' + method)
427                 } catch (BpmnError e) {
428                         throw e;
429                 } catch (Exception e) {
430                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
431                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
432                 }
433         }
434
435         /**
436          * Validates the request, request id and service instance id.  If a problem is found,
437          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
438          * method also sets up the log context for the workflow.
439          * @param execution the execution
440          * @return the validated request
441          */
442         public String validateInfraRequest(DelegateExecution execution) {
443                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
444                         'execution=' + execution.getId() +
445                         ')'
446
447                 msoLogger.trace('Entered ' + method)
448
449                 String processKey = getProcessKey(execution);
450                 def prefix = execution.getVariable("prefix")
451
452                 if (prefix == null) {
453                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
454                 }
455
456                 try {
457                         def request = execution.getVariable(prefix + 'Request')
458
459                         if (request == null) {
460                                 request = execution.getVariable(processKey + 'Request')
461
462                                 if (request == null) {
463                                         request = execution.getVariable('bpmnRequest')
464                                 }
465
466                                 setVariable(execution, processKey + 'Request', null);
467                                 setVariable(execution, 'bpmnRequest', null);
468                                 setVariable(execution, prefix + 'Request', request);
469                         }
470
471                         if (request == null) {
472                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
473                         }
474
475                         /*
476
477                         def requestId = execution.getVariable("mso-request-id")
478
479                         if (requestId == null) {
480                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
481                         }
482
483                         setVariable(execution, prefix + 'requestId', requestId)
484
485                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
486
487                         if (serviceInstanceId == null) {
488                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
489                         }
490
491                         utils.logContext(requestId, serviceInstanceId)
492                         */
493                         msoLogger.debug('Incoming message: ' + System.lineSeparator() + request)
494                         msoLogger.trace('Exited ' + method)
495                         return request
496                 } catch (BpmnError e) {
497                         throw e;
498                 } catch (Exception e) {
499                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
500                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
501                 }
502         }
503
504 }