Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / 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                         def tenantId = cloudConfiguration.tenantId
195                         execution.setVariable(prefix + 'tenantId', tenantId)
196
197                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
198                         execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId)
199
200                         execution.setVariable(prefix + 'sdncVersion', '1702')
201
202                         execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false)
203
204
205
206
207                         def source = reqMap.requestDetails?.requestInfo?.source
208                         execution.setVariable(prefix + "source", source)
209
210                         //For Completion Handler & Fallout Handler
211                         String requestInfo =
212                                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
213                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
214                                         <action>UPDATE</action>
215                                         <source>${MsoUtils.xmlEscape(source)}</source>
216                                    </request-info>"""
217
218                         execution.setVariable(prefix + "requestInfo", requestInfo)
219
220                         //backoutOnFailure
221
222                         //msoLogger.debug('RequestInfo: ' + execution.getVariable(prefix + "requestInfo"))
223
224                         //msoLogger.trace('Exited ' + method)
225
226                 }
227                 catch(groovy.json.JsonException je) {
228                         //msoLogger.debug(" Request is not in JSON format.")
229                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
230                 }
231                 catch(Exception e) {
232                         String restFaultMessage = e.getMessage()
233                         //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
234                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
235                 }
236         }
237
238         /**
239          * Prepare and send the synchronous response for this flow.
240          *
241          * @param execution The flow's execution instance.
242          */
243         public void sendSynchResponse(DelegateExecution execution) {
244                 System.out.print("*****************************SendSynchResponse**************************")
245
246                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
247                                 'execution=' + execution.getId() +
248                                 ')'
249
250                 //msoLogger.trace('Entered ' + method)
251
252
253                 try {
254                         def requestInfo = execution.getVariable('UPDVfModI_requestInfo')
255                         def requestId = execution.getVariable('UPDVfModI_requestId')
256                         def source = execution.getVariable('UPDVfModI_source')
257                         
258                         def progress = getNodeTextForce(requestInfo, 'progress')
259                         if (progress.isEmpty()) {
260                                 progress = '0'
261                         }
262                         def startTime = getNodeTextForce(requestInfo, 'start-time')
263                         if (startTime.isEmpty()) {
264                                 startTime = System.currentTimeMillis()
265                         }
266                         // RESTResponse (for API Handler (APIH) Reply Task)
267                         def vfModuleId = execution.getVariable("vfModuleId")
268                         String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim()
269                         sendWorkflowResponse(execution, 200, synchResponse)
270                         //msoLogger.trace('Exited ' + method)
271                 } catch (BpmnError e) {
272                         throw e;
273                 } catch (Exception e) {
274                         //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
275                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
276                 }
277         }
278
279         //check to see if the Pserver Flag is locked
280         public void checkPserverFlag(DelegateExecution execution) {
281
282                 System.out.println("*****************************CheckingPserverFlag*************************")
283                 String vnfId = (String)execution.getVariable('vnfId')
284                 String uuid = (String)execution.getVariable('moduleUuid')
285                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
286                 boolean flag = aaiVI.isPhysicalServerLocked(vnfId, uuid)
287         }
288
289         //check to see if the VFFlag is locked
290         public void vfFlagCheck(DelegateExecution execution) {
291
292                 System.out.print("*****************************VfFlagCheck*************************")
293                 String vnfId = (String)execution.getVariable('vnfId')
294                 String uuid = (String)execution.getVariable('moduleUuid')
295                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
296                 boolean flag = aaiVI.isVNFLocked(vnfId, uuid)
297
298         }
299         //lock the VF Flag
300         public void vfFlagSet(DelegateExecution execution) {
301
302                 System.out.print("*****************************VfFlagSet*************************")
303                 String vnfId = (String)execution.getVariable('vnfId')
304                 String uuid = (String)execution.getVariable('moduleUuid')
305                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
306                 aaiVI.updateVnfToLocked(vnfId,uuid);
307                 
308         }
309
310         //Lock AppC
311         public void lockAppC(DelegateExecution execution) {
312
313                 System.out.print("*****************************lockAppC*************************")
314                 def vfModuleId = ""
315                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
316                 def status = aCC.runCommand("Lock",vfModuleId)
317
318
319         }
320         //run health check
321         public void healthCheckAppC(DelegateExecution execution) {
322
323                 System.out.print("*****************************healthCheckAppC*************************")
324                 def vfModuleId = ""
325                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
326                 def status = aCC.runCommand("HealthCheck",vfModuleId)
327
328         }
329         //SDNO health diagnostic
330         public void healthDiagnosticSDNO(DelegateExecution execution) {
331
332                 System.out.print("*****************************healthDiagnosticSDNO is currently ignored*************************")
333                 //SDNOValidatorImpl.healthDiagnostic("","");
334
335         }
336         //stop VF module controller
337         public void stopVfModuleController(DelegateExecution execution) {
338
339                 System.out.print("*****************************stopVfModuleController*************************")
340                 def vfModuleId = ""
341                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
342                 def status = aCC.runCommand("Stop",vfModuleId)
343
344
345         }
346
347         public void doUpdateVfModulePrep(DelegateExecution execution) {
348
349                 System.out.print("*****************************doUpdateVfModulePrep*************************")
350                 def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' +
351                                 'execution=' + execution.getId() +
352                                 ')'
353
354                 //msoLogger.trace('Entered ' + method)
355
356                 try {
357
358                         //msoLogger.trace('Exited ' + method)
359                 } catch (BpmnError e) {
360                         throw e;
361                 } catch (Exception e) {
362                         //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
363                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage())
364
365                 }
366
367         }
368
369         public void completionHandlerPrep(DelegateExecution execution,String resultVar) {
370
371                 System.out.print("*****************************completionHandlerPrep*************************")
372                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
373                                 'execution=' + execution.getId() +
374                                 ', resultVar=' + resultVar +
375                                 ')'
376
377                 //msoLogger.trace('Entered ' + method)
378
379                 try {
380                         def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo')
381
382                         String content = """
383                                         <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
384                                                         xmlns:reqtype="http://org.onap/so/request/types/v1">
385                                                 ${requestInfo}
386                                                 <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
387                                         </sdncadapterworkflow:MsoCompletionRequest>
388                                 """
389
390                         content = utils.formatXml(content)
391                         //msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content)
392                         execution.setVariable(resultVar, content)
393
394                         //msoLogger.trace('Exited ' + method)
395                 } catch (BpmnError e) {
396                         throw e;
397                 } catch (Exception e) {
398                         //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
399                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
400
401                 }
402
403         }
404
405         public void healthCheckController(DelegateExecution execution) {
406
407                 System.out.print("*****************************healthCheckController*************************")
408                 def vfModuleId = ""
409                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
410                 def status = aCC.runCommand("HealthCheck",vfModuleId)
411
412         }
413
414         public void startVfModuleController(DelegateExecution execution) {
415
416                 System.out.print("*****************************startVfModuleController*************************")
417                 def vfModuleId = ""
418                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
419                 def status = aCC.runCommand("Start",vfModuleId)
420
421         }
422
423         public void vFFlagUnset(DelegateExecution execution) {
424
425                 System.out.print("*****************************vFFlagUnset*************************")
426                 String vnfId = (String)execution.getVariable('vnfId')
427                 String uuid = (String)execution.getVariable('moduleUuid')
428                 AAIValidatorImpl aaiVI = new AAIValidatorImpl()
429                 aaiVI.updateVnfToUnLocked(vnfId,uuid);
430
431
432         }
433
434         public void unlockAppC(DelegateExecution execution) {
435
436                 System.out.print("*****************************unlockAppC*************************")
437                 def vfModuleId = ""
438                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
439                 def status = aCC.runCommand("Unlock",vfModuleId)
440
441         }
442
443         public void postUpgradeHealthCheckController(DelegateExecution execution) {
444
445                 System.out.print("*****************************postUpgradeHealthCheckController*************************")
446                 def vfModuleId = ""
447                 ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties())
448                 def status = aCC.runCommand("HealthCheck",vfModuleId)
449
450         }
451
452     Properties getLCMProperties() {
453         Properties properties = new Properties()
454
455         properties.put("topic.read", UrnPropertiesReader.getVariable("appc.client.topic.read.name"))
456         properties.put("topic.read.timeout", UrnPropertiesReader.getVariable("appc.client.topic.read.timeout"))
457         properties.put("client.response.timeout", UrnPropertiesReader.getVariable("appc.client.response.timeout"))
458         properties.put("topic.write", UrnPropertiesReader.getVariable("appc.client.topic.write"))
459         properties.put("poolMembers", UrnPropertiesReader.getVariable("appc.client.poolMembers"))
460         properties.put("client.key", UrnPropertiesReader.getVariable("appc.client.key"))
461         properties.put("client.secret", UrnPropertiesReader.getVariable("appc.client.secret"))
462         properties.put("client.name", "MSO")
463         properties.put("service", UrnPropertiesReader.getVariable("appc.client.service"))
464         return properties
465     }
466
467 }
468