f04fa002feac6e002bc8931f8c9640de726d7638
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / UpdateVfModuleInfraV2.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import groovy.json.JsonOutput
26 import groovy.json.JsonSlurper
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.onap.so.bpmn.common.scripts.ExceptionUtil
30 import org.onap.so.bpmn.common.scripts.MsoUtils
31 import org.onap.so.bpmn.core.UrnPropertiesReader
32 import org.onap.so.client.aai.AAIValidatorImpl
33 import org.onap.so.client.appc.ApplicationControllerClient
34 import org.slf4j.Logger
35 import org.slf4j.LoggerFactory
36
37 public class UpdateVfModuleInfraV2 {
38     private static final Logger logger = LoggerFactory.getLogger(UpdateVfModuleInfraV2.class)
39
40         ExceptionUtil exceptionUtil = new ExceptionUtil()
41
42         boolean preProcessRequestCheck = true;
43         boolean sendSynchResponseCheck = true;
44         boolean checkPserverFlagCheck = true;
45         boolean vfFlagCheckSetCheck = true;
46         boolean lockAppCCheck = true;
47         boolean healthDiagnosticSDNOCheck = true;
48         boolean healthCheckAppCCheck = true;
49         boolean stopVfModuleControllerCheck = true;
50         boolean healthCheckControllerCheck = true;
51         boolean doUpdateVfModulePrepCheck = true;
52         boolean completionHandlerPrepCheck = true;
53         boolean startVfModuleControllerCheck = true;
54         boolean vFFlagUnsetCheck = true;
55         boolean unlockAppCCheck = true;
56         boolean postUpgradeHealthCheckControllerCheck = true;
57
58
59
60         public void initProcessVariables(DelegateExecution execution) {
61                 execution.setVariable('prefix', 'UPDVfModI_')
62                 execution.setVariable('UPDVfModI_Request', null)
63                 execution.setVariable('UPDVfModI_requestInfo', null)
64                 execution.setVariable('UPDVfModI_requestId', null)
65                 execution.setVariable('UPDVfModI_source', null)
66                 execution.setVariable('UPDVfModI_vnfInputs', null)
67                 execution.setVariable('UPDVfModI_vnfId', null)
68                 execution.setVariable('UPDVFModI_moduleUuid', null)
69                 execution.setVariable('UPDVfModI_vfModuleId', null)
70                 execution.setVariable('UPDVfModI_tenantId', null)
71                 execution.setVariable('UPDVfModI_volumeGroupId', null)
72                 execution.setVariable('UPDVfModI_vnfParams', null)
73                 execution.setVariable('UPDVfModI_updateInfraRequest', null)
74                 execution.setVariable('UpdateVfModuleSuccessIndicator', false)
75         }
76
77         /**
78          * Check for missing elements in the received request.
79          *
80          * @param execution The flow's execution instance.
81          */
82         public void preProcessRequest(DelegateExecution execution) {
83         logger.debug("*****************************PreProcessRequest**************************")
84
85                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
86                                 'execution=' + execution.getId() +
87                                 ')'
88
89                 //logger.trace('Entered ' + method)
90
91                 initProcessVariables(execution)
92
93                 def prefix = "UPDVfModI_"
94
95                 def incomingRequest = execution.getVariable('bpmnRequest')
96
97                 //logger.debug("Incoming Infra Request: " + incomingRequest)
98                 try {
99                         def jsonSlurper = new JsonSlurper()
100                         def jsonOutput = new JsonOutput()
101                         Map reqMap = jsonSlurper.parseText(incomingRequest)
102                         //logger.debug(" Request is in JSON format.")
103
104                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
105                         def vnfId = execution.getVariable('vnfId')
106                         def moduleUuid = execution.getVariable('moduleUuid')
107                         execution.setVariable(prefix + 'moduleUuid',moduleUuid)
108                         execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId)
109                         execution.setVariable(prefix+'vnfId', vnfId)
110                         execution.setVariable("isVidRequest", "true")
111
112                         def vnfName = ''
113                         def asdcServiceModelVersion = ''
114                         def serviceModelInfo = null
115                         def vnfModelInfo = null
116
117                         def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList
118
119                         if (relatedInstanceList != null) {
120                                 relatedInstanceList.each {
121                                         if (it.relatedInstance.modelInfo?.modelType == 'service') {
122                                                 asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
123                                                 serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
124                                         }
125                                         if (it.relatedInstance.modelInfo.modelType == 'vnf') {
126                                                 vnfName = it.relatedInstance.instanceName ?: ''
127                                                 vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
128                                         }
129                                 }
130                         }
131
132                         execution.setVariable(prefix + 'vnfName', vnfName)
133                         execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion)
134                         execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo)
135                         execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo)
136
137                         def vnfType = execution.getVariable('vnfType')
138                         execution.setVariable(prefix + 'vnfType', vnfType)
139                         def vfModuleId = execution.getVariable('vfModuleId')
140                         execution.setVariable(prefix + 'vfModuleId', vfModuleId)
141                         def volumeGroupId = execution.getVariable('volumeGroupId')
142                         execution.setVariable(prefix + 'volumeGroupId', volumeGroupId)
143                         def userParams = reqMap.requestDetails?.requestParameters?.userParams
144
145                         Map<String, String> userParamsMap = [:]
146                         if (userParams != null) {
147                                 userParams.each { userParam ->
148                                         userParamsMap.put(userParam.name, userParam.value.toString())
149                                 }
150                         }
151
152                         //logger.debug('Processed user params: ' + userParamsMap)
153
154                         execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap)
155
156                         def isBaseVfModule = "false"
157                         if (execution.getVariable('isBaseVfModule') == true) {
158                                 isBaseVfModule = "true"
159                         }
160
161                         execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule)
162
163                         def requestId = execution.getVariable("mso-request-id")
164                         execution.setVariable(prefix + 'requestId', requestId)
165
166                         def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo)
167                         execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo)
168
169                         def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback
170
171
172                         def backoutOnFailure = ""
173                         if(suppressRollback != null){
174                                 if ( suppressRollback == true) {
175                                         backoutOnFailure = "false"
176                                 } else if ( suppressRollback == false) {
177                                         backoutOnFailure = "true"
178                                 }
179                         }
180
181                         execution.setVariable('disableRollback', suppressRollback)
182
183                         def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null
184                         execution.setVariable(prefix + 'vfModuleName', vfModuleName)
185
186                         def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: ''
187                         execution.setVariable(prefix + 'serviceId', serviceId)
188
189                         def usePreload = reqMap.requestDetails?.requestParameters?.usePreload
190                         execution.setVariable(prefix + 'usePreload', usePreload)
191
192                         def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration
193                         def lcpCloudRegionId    = cloudConfiguration.lcpCloudRegionId
194                         execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId)
195                         
196                         def cloudOwner  = cloudConfiguration.cloudOwner
197                         execution.setVariable(prefix + 'cloudOwner', cloudOwner)
198                         
199                         def tenantId = cloudConfiguration.tenantId
200                         execution.setVariable(prefix + 'tenantId', tenantId)
201
202                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
203                         execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId)
204
205                         execution.setVariable(prefix + 'sdncVersion', '1702')
206
207                         execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false)
208
209
210
211
212                         def source = reqMap.requestDetails?.requestInfo?.source
213                         execution.setVariable(prefix + "source", source)
214
215                         //For Completion Handler & Fallout Handler
216                         String requestInfo =
217                                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
218                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
219                                         <action>UPDATE</action>
220                                         <source>${MsoUtils.xmlEscape(source)}</source>
221                                    </request-info>"""
222
223                         execution.setVariable(prefix + "requestInfo", requestInfo)
224
225                         //backoutOnFailure
226
227                         //logger.debug('RequestInfo: ' + execution.getVariable(prefix + "requestInfo"))
228
229                         //logger.trace('Exited ' + method)
230
231                 }
232                 catch(groovy.json.JsonException je) {
233                         //logger.debug(" Request is not in JSON format.")
234                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
235                 }
236                 catch(Exception e) {
237                         String restFaultMessage = e.getMessage()
238                         //logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
239                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
240                 }
241         }
242
243         /**
244          * Prepare and send the synchronous response for this flow.
245          *
246          * @param execution The flow's execution instance.
247          */
248         public void sendSynchResponse(DelegateExecution execution) {
249         logger.debug("*****************************SendSynchResponse**************************")
250
251                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
252                                 'execution=' + execution.getId() +
253                                 ')'
254
255                 //logger.trace('Entered ' + method)
256
257
258                 try {
259                         def requestInfo = execution.getVariable('UPDVfModI_requestInfo')
260                         def requestId = execution.getVariable('UPDVfModI_requestId')
261                         def source = execution.getVariable('UPDVfModI_source')
262                         
263                         def progress = getNodeTextForce(requestInfo, 'progress')
264                         if (progress.isEmpty()) {
265                                 progress = '0'
266                         }
267                         def startTime = getNodeTextForce(requestInfo, 'start-time')
268                         if (startTime.isEmpty()) {
269                                 startTime = System.currentTimeMillis()
270                         }
271                         // RESTResponse (for API Handler (APIH) Reply Task)
272                         def vfModuleId = execution.getVariable("vfModuleId")
273                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
274                         sendWorkflowResponse(execution, 200, synchResponse)
275                         //logger.trace('Exited ' + method)
276                 } catch (BpmnError e) {
277                         throw e;
278                 } catch (Exception e) {
279                         //logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
280                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
281                 }
282         }
283
284         //check to see if the Pserver Flag is locked
285         public void checkPserverFlag(DelegateExecution execution) {
286
287         logger.debug("*****************************CheckingPserverFlag*************************")
288                 String vnfId = (String)execution.getVariable('vnfId')
289                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
290                 boolean flag = aaiVI.isPhysicalServerLocked(vnfId)
291         }
292
293         //check to see if the VFFlag is locked
294         public void vfFlagCheck(DelegateExecution execution) {
295
296         logger.debug("*****************************VfFlagCheck*************************")
297                 String vnfId = (String)execution.getVariable('vnfId')
298                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
299                 boolean flag = aaiVI.isVNFLocked(vnfId)
300
301         }
302         //lock the VF Flag
303         public void vfFlagSet(DelegateExecution execution) {
304
305         logger.debug("*****************************VfFlagSet*************************")
306                 String vnfId = (String)execution.getVariable('vnfId')
307                 String uuid = (String)execution.getVariable('moduleUuid')
308                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
309                 aaiVI.updateVnfToLocked(vnfId,uuid);
310                 
311         }
312
313         //Lock AppC
314         public void lockAppC(DelegateExecution execution) {
315
316         logger.debug("*****************************lockAppC*************************")
317                 def vfModuleId = ""
318                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
319                 def status = aCC.runCommand("Lock",vfModuleId)
320
321
322         }
323         //run health check
324         public void healthCheckAppC(DelegateExecution execution) {
325
326         logger.debug("*****************************healthCheckAppC*************************")
327                 def vfModuleId = ""
328                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
329                 def status = aCC.runCommand("HealthCheck",vfModuleId)
330
331         }
332         //SDNO health diagnostic
333         public void healthDiagnosticSDNO(DelegateExecution execution) {
334
335         logger.debug("*****************************healthDiagnosticSDNO is currently ignored*************************")
336                 //SDNOValidatorImpl.healthDiagnostic("","");
337
338         }
339         //stop VF module controller
340         public void stopVfModuleController(DelegateExecution execution) {
341
342         logger.debug("*****************************stopVfModuleController*************************")
343                 def vfModuleId = ""
344                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
345                 def status = aCC.runCommand("Stop",vfModuleId)
346
347
348         }
349
350         public void doUpdateVfModulePrep(DelegateExecution execution) {
351
352         logger.debug("*****************************doUpdateVfModulePrep*************************")
353                 def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' +
354                                 'execution=' + execution.getId() +
355                                 ')'
356
357                 //logger.trace('Entered ' + method)
358
359                 try {
360
361                         //logger.trace('Exited ' + method)
362                 } catch (BpmnError e) {
363                         throw e;
364                 } catch (Exception e) {
365                         //logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
366                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage())
367
368                 }
369
370         }
371
372         public void completionHandlerPrep(DelegateExecution execution,String resultVar) {
373
374         logger.debug("*****************************completionHandlerPrep*************************")
375                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
376                                 'execution=' + execution.getId() +
377                                 ', resultVar=' + resultVar +
378                                 ')'
379
380                 //logger.trace('Entered ' + method)
381
382                 try {
383                         def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo')
384
385                         String content = """
386                                         <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
387                                                         xmlns:reqtype="http://org.onap/so/request/types/v1">
388                                                 ${requestInfo}
389                                                 <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
390                                         </sdncadapterworkflow:MsoCompletionRequest>
391                                 """
392
393                         content = utils.formatXml(content)
394                         //logger.debug(resultVar + ' = ' + System.lineSeparator() + content)
395                         execution.setVariable(resultVar, content)
396
397                         //logger.trace('Exited ' + method)
398                 } catch (BpmnError e) {
399                         throw e;
400                 } catch (Exception e) {
401                         //logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
402                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
403
404                 }
405
406         }
407
408         public void healthCheckController(DelegateExecution execution) {
409
410         logger.debug("*****************************healthCheckController*************************")
411                 def vfModuleId = ""
412                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
413                 def status = aCC.runCommand("HealthCheck",vfModuleId)
414
415         }
416
417         public void startVfModuleController(DelegateExecution execution) {
418
419         logger.debug("*****************************startVfModuleController*************************")
420                 def vfModuleId = ""
421                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
422                 def status = aCC.runCommand("Start",vfModuleId)
423
424         }
425
426         public void vFFlagUnset(DelegateExecution execution) {
427
428         logger.debug("*****************************vFFlagUnset*************************")
429                 String vnfId = (String)execution.getVariable('vnfId')
430                 String uuid = (String)execution.getVariable('moduleUuid')
431                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
432                 aaiVI.updateVnfToUnLocked(vnfId,uuid);
433
434
435         }
436
437         public void unlockAppC(DelegateExecution execution) {
438
439         logger.debug("*****************************unlockAppC*************************")
440                 def vfModuleId = ""
441                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
442                 def status = aCC.runCommand("Unlock",vfModuleId)
443
444         }
445
446         public void postUpgradeHealthCheckController(DelegateExecution execution) {
447
448         logger.debug("*****************************postUpgradeHealthCheckController*************************")
449                 def vfModuleId = ""
450                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
451                 def status = aCC.runCommand("HealthCheck",vfModuleId)
452
453         }
454
455     Properties getLCMProperties() {
456         Properties properties = new Properties()
457
458         properties.put("topic.read", UrnPropertiesReader.getVariable("appc.client.topic.read.name"))
459         properties.put("topic.read.timeout", UrnPropertiesReader.getVariable("appc.client.topic.read.timeout"))
460         properties.put("client.response.timeout", UrnPropertiesReader.getVariable("appc.client.response.timeout"))
461         properties.put("topic.write", UrnPropertiesReader.getVariable("appc.client.topic.write"))
462         properties.put("poolMembers", UrnPropertiesReader.getVariable("appc.client.poolMembers"))
463         properties.put("client.key", UrnPropertiesReader.getVariable("appc.client.key"))
464         properties.put("client.secret", UrnPropertiesReader.getVariable("appc.client.secret"))
465         properties.put("client.name", "MSO")
466         properties.put("service", UrnPropertiesReader.getVariable("appc.client.service"))
467         return properties
468     }
469
470 }
471