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