Merge "Fixing SO-Monitoring UI tests"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / UpdateVnfInfra.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  *      http://www.apache.org/licenses/LICENSE-2.0
11  * 
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  */
19
20 package org.onap.so.bpmn.infrastructure.scripts
21
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.onap.appc.client.lcm.model.Action;
25 import org.onap.so.bpmn.common.scripts.ExceptionUtil
26 import org.onap.so.bpmn.common.scripts.MsoUtils
27 import org.onap.so.bpmn.core.domain.ModelInfo
28 import org.onap.so.bpmn.core.domain.ServiceDecomposition
29 import org.onap.so.bpmn.core.domain.VnfResource
30 import org.onap.so.bpmn.core.json.JsonUtils
31 import org.onap.so.client.aai.*
32 import org.onap.so.logger.MessageEnum
33 import org.onap.so.logger.MsoLogger
34
35 import groovy.json.JsonOutput
36 import groovy.json.JsonSlurper
37
38 public class UpdateVnfInfra extends VnfCmBase {
39         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVnfInfra.class);
40
41         ExceptionUtil exceptionUtil = new ExceptionUtil()
42         JsonUtils jsonUtils = new JsonUtils()   
43         def prefix = "UPDVnfI_"
44
45         /**
46          * Initialize the flow's variables.
47          *
48          * @param execution The flow's execution instance.
49          */
50         public void initProcessVariables(DelegateExecution execution) {
51                 execution.setVariable('prefix', 'UPDVnfI_')
52                 execution.setVariable('Request', null)          
53                 execution.setVariable('source', null)
54                 execution.setVariable('vnfInputs', null)                        
55                 execution.setVariable('tenantId', null)         
56                 execution.setVariable('vnfParams', null)                
57                 execution.setVariable('controllerType', null)           
58                 execution.setVariable('UpdateVnfSuccessIndicator', false)
59                 execution.setVariable('serviceType', null)
60                 execution.setVariable('nfRole', null)
61                 execution.setVariable('currentActivity', 'UPDVnfI')
62                 execution.setVariable('workStep', null)
63                 execution.setVariable('failedActivity', null)
64                 execution.setVariable('errorCode', "0")
65                 execution.setVariable('errorText', null)
66                 execution.setVariable('healthCheckIndex0', 0)
67                 execution.setVariable('healthCheckIndex1', 1)
68                 execution.setVariable("rollbackSetClosedLoopDisabledFlag", false)
69                 execution.setVariable("rollbackVnfStop", false)
70                 execution.setVariable("rollbackVnfLock", false)
71                 execution.setVariable("rollbackQuiesceTraffic", false)
72                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", false)
73         }
74
75         /**
76          * Check for missing elements in the received request.
77          *
78          * @param execution The flow's execution instance.
79          */
80         public void preProcessRequest(DelegateExecution execution) {
81                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
82                 'execution=' + execution.getId() +
83                 ')'
84                 initProcessVariables(execution)
85
86                 msoLogger.trace('Entered ' + method)
87
88                 initProcessVariables(execution)         
89
90                 def incomingRequest = execution.getVariable('bpmnRequest')
91
92                 msoLogger.debug("Incoming Infra Request: " + incomingRequest)
93                 try {
94                         def jsonSlurper = new JsonSlurper()
95                         def jsonOutput = new JsonOutput()
96                         Map reqMap = jsonSlurper.parseText(incomingRequest)
97                         msoLogger.debug(" Request is in JSON format.")
98                         
99                         execution.setVariable("isVidRequest", "true")
100                         execution.setVariable('serviceType', 'Mobility')
101                         execution.setVariable('actionLock', Action.Lock)
102                         execution.setVariable('actionUnlock', Action.Unlock)
103                         execution.setVariable('actionHealthCheck', Action.HealthCheck)
104                         execution.setVariable('actionStart', Action.Start)
105                         execution.setVariable('actionStop', Action.Stop)
106                         
107                         def asdcServiceModelVersion = ''
108                         def serviceModelInfo = null
109                         
110                         def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList
111                                                 
112                         if (relatedInstanceList != null) {
113                                 relatedInstanceList.each {
114                                         if (it.relatedInstance.modelInfo?.modelType == 'service') {
115                                                 msoLogger.debug("PROCESSING SERVICE INFO")
116                                                 asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
117                                                 serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo)
118                                                 msoLogger.debug("ServiceModelInfo: " + serviceModelInfo)
119                                                 def modelInvariant = jsonUtils.getJsonValue(serviceModelInfo, "modelInvariantUuid")
120                                                 msoLogger.debug("modelInvariant: " + modelInvariant)
121                                         }
122                                         
123                                 }
124                         }               
125                         
126                         execution.setVariable('asdcServiceModelVersion', asdcServiceModelVersion)
127                         execution.setVariable('serviceModelInfo', serviceModelInfo)
128                         def vnfModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo)
129                         execution.setVariable('vnfModelInfo', vnfModelInfo)
130                         def vnfModelInvariantUuid = jsonUtils.getJsonValue(vnfModelInfo, "modelInvariantUuid")
131                         execution.setVariable('vnfModelInvariantUuid', vnfModelInvariantUuid)   
132                         msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid)      
133                         
134                         def vnfType = execution.getVariable('vnfType')
135                         execution.setVariable('vnfType', vnfType)
136                         
137
138                         def controllerType = reqMap.requestDetails?.requestParameters?.controllerType
139                         execution.setVariable('controllerType', controllerType)
140                         
141                         msoLogger.debug('Controller Type: ' + controllerType)
142                         
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                         msoLogger.debug('Processed user params: ' + userParamsMap)              
153                         
154                         execution.setVariable('vfModuleInputParams', userParamsMap)                     
155                                                 
156                         def requestId = execution.getVariable("mso-request-id")
157                         execution.setVariable('requestId', requestId)
158                         execution.setVariable('msoRequestId', requestId)
159                         
160                         
161                         def vnfName = reqMap.requestDetails?.requestInfo?.instanceName ?: null
162                         execution.setVariable('vnfName', vnfName)
163                         
164                         def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null
165                         execution.setVariable('requestorId', requestorId)
166                         
167                         def usePreload = reqMap.requestDetails?.requestParameters?.usePreload
168                         execution.setVariable('usePreload', usePreload)
169                         
170                         def cloudConfiguration = jsonOutput.toJson(reqMap.requestDetails?.cloudConfiguration)                   
171                         def lcpCloudRegionId    = jsonUtils.getJsonValue(cloudConfiguration, "lcpCloudRegionId")
172                         execution.setVariable('lcpCloudRegionId', lcpCloudRegionId)
173                         def cloudOwner  = jsonUtils.getJsonValue(cloudConfiguration, "cloudOwner")
174                         execution.setVariable('cloudOwner', cloudOwner)
175                         def tenantId = jsonUtils.getJsonValue(cloudConfiguration, "tenantId")
176                         execution.setVariable('tenantId', tenantId)
177                         
178                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
179                         execution.setVariable('globalSubscriberId', globalSubscriberId)
180                         
181                         execution.setVariable('sdncVersion', '1702')
182
183                         execution.setVariable("UpdateVnfInfraSuccessIndicator", false)
184                                                 
185
186                         
187                         def source = reqMap.requestDetails?.requestInfo?.source
188                         execution.setVariable("source", source)
189                         
190                         //For Completion Handler & Fallout Handler
191                         String requestInfo =
192                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
193                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
194                                         <action>UPDATE</action>
195                                         <source>${MsoUtils.xmlEscape(source)}</source>
196                                    </request-info>"""
197                         
198                         execution.setVariable("requestInfo", requestInfo)                       
199                         
200                         msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo"))         
201                         
202                         msoLogger.trace('Exited ' + method)
203
204                 }
205                 catch(groovy.json.JsonException je) {
206                         msoLogger.debug(" Request is not in JSON format.")
207                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
208
209                 }
210                 catch(Exception e) {
211                         String restFaultMessage = e.getMessage()
212                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
213                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
214                 }       
215         }
216
217         /**
218          * Prepare and send the sychronous response for this flow.
219          *
220          * @param execution The flow's execution instance.
221          */
222         public void sendSynchResponse(DelegateExecution execution) {
223                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
224                         'execution=' + execution.getId() +
225                         ')'
226
227                 msoLogger.trace('Entered ' + method)
228
229
230                 try {
231                         def requestInfo = execution.getVariable('requestInfo')
232                         def requestId = execution.getVariable('requestId')
233                         def source = execution.getVariable('source')
234                         def progress = getNodeTextForce(requestInfo, 'progress')
235                         if (progress.isEmpty()) {
236                                 progress = '0'
237                         }
238                         def startTime = getNodeTextForce(requestInfo, 'start-time')
239                         if (startTime.isEmpty()) {
240                                 startTime = System.currentTimeMillis()
241                         }
242
243                         // RESTResponse (for API Handler (APIH) Reply Task)
244                         def vnfId = execution.getVariable("vnfId")
245                         String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim()
246
247                         sendWorkflowResponse(execution, 200, synchResponse)
248
249                         msoLogger.trace('Exited ' + method)
250                 } catch (BpmnError e) {
251                         throw e;
252                 } catch (Exception e) {
253                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
254                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
255                 }
256         }
257         
258         
259
260         /**
261          * Get VnfResource decomposition object for this VNF.
262          *      
263          *
264          * @param execution The flow's execution instance.
265          */
266         public void getVnfResourceDecomposition(DelegateExecution execution) {
267                 def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' +
268                         'execution=' + execution.getId() +
269                         ')'
270
271                 msoLogger.trace('Entered ' + method)
272
273                 try {
274                         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
275                         String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid')
276                         msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid)
277                         List<VnfResource> vnfResources = serviceDecomposition.getVnfResources()
278                         
279                         for (i in 0..vnfResources.size()-1) {
280                                 ModelInfo modelInfo = vnfResources[i].getModelInfo()
281                                 String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid()
282                                 msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition)
283                                 
284                                 if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) {
285                                         VnfResource vnfResourceDecomposition = vnfResources[i]
286                                         execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition)
287                                         def nfRole = vnfResourceDecomposition.getNfRole()                                       
288                                         execution.setVariable('nfRole', nfRole)
289                                         msoLogger.debug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString())                                 
290                                         break
291                                 }
292                                 else {
293                                         //exception!
294                                 }
295                                 
296                         }
297
298                         msoLogger.trace('Exited ' + method)
299                 } catch (BpmnError e) {
300                         throw e;
301                 } catch (Exception e) {
302                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
303                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage())
304                 }
305         }
306         
307         /**
308          * Check if this VNF is already in maintenance in A&AI.
309          *
310          *
311          * @param execution The flow's execution instance.
312          */
313         public void checkIfVnfInMaintInAAI(DelegateExecution execution) {
314                 def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' +
315                         'execution=' + execution.getId() +
316                         ')'
317
318                 execution.setVariable('errorCode', "0")
319                 execution.setVariable("workStep", "checkIfVnfInMaintInAAI")
320                 execution.setVariable("failedActivity", "AAI")
321                 msoLogger.trace('Entered ' + method)
322
323                 try {
324                         def transactionLoggingUuid = UUID.randomUUID().toString()
325                         AAIRestClientImpl client = new AAIRestClientImpl()
326                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
327                         aaiValidator.setClient(client)
328                         def vnfId = execution.getVariable("vnfId")
329                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid)
330                         msoLogger.debug("isInMaint result: " + isInMaint)
331                         execution.setVariable('isVnfInMaintenance', isInMaint)
332                         
333                         if (isInMaint) {
334                                 execution.setVariable("errorCode", "1003")
335                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
336                         }
337
338
339                         msoLogger.trace('Exited ' + method)
340                 } catch (BpmnError e) {
341                         throw e;
342                 } catch (Exception e) {
343                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);          
344                         execution.setVariable("errorCode", "1002")
345                         execution.setVariable("errorText", e.getMessage())
346                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
347                 }
348         }
349         
350         
351         /**
352          * Check if this VNF's pservers are locked in A&AI.
353          *
354          *
355          * @param execution The flow's execution instance.
356          */
357         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
358                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
359                         'execution=' + execution.getId() +
360                         ')'
361
362                 execution.setVariable('errorCode', "0")
363                 msoLogger.trace('Entered ' + method)
364                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
365                 execution.setVariable("failedActivity", "AAI")
366
367                 try {
368                         def transactionLoggingUuid = UUID.randomUUID().toString()
369                         AAIRestClientImpl client = new AAIRestClientImpl()
370                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
371                         aaiValidator.setClient(client)
372                         def vnfId = execution.getVariable("vnfId")                      
373                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid)
374                         msoLogger.debug("areLocked result: " + areLocked)
375                         execution.setVariable('arePserversLocked', areLocked)
376                         
377                         if (areLocked) {
378                                 execution.setVariable("errorCode", "1003")
379                                 execution.setVariable("errorText", "pServers are locked in A&AI")
380                         }
381
382                         msoLogger.trace('Exited ' + method)
383                 } catch (BpmnError e) {
384                         throw e;
385                 } catch (Exception e) {
386                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
387                         execution.setVariable("errorCode", "1002")
388                         execution.setVariable("errorText", e.getMessage())
389                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
390                 }
391         }
392         
393         /**
394          * Set inMaint flag for this VNF to the specified value in A&AI.
395          *
396          *
397          * @param execution The flow's execution instance.
398          * @param inMaint The boolean value of the flag to set
399          */
400         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
401                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
402                         'execution=' + execution.getId() +
403                         ')'
404
405                 execution.setVariable('errorCode', "0")
406                 msoLogger.trace('Entered ' + method)
407                 if (inMaint) {
408                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
409                 }
410                 else {
411                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
412                 }
413                 execution.setVariable("failedActivity", "AAI")
414
415                 try {
416                         def transactionLoggingUuid = UUID.randomUUID().toString()
417                         AAIRestClientImpl client = new AAIRestClientImpl()
418                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
419                         aaiUpdator.setClient(client)
420                         def vnfId = execution.getVariable("vnfId")
421                         if (inMaint) {
422                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
423                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
424                         }
425                         else {
426                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
427                         }
428                                                         
429                         msoLogger.trace('Exited ' + method)
430                 } catch (BpmnError e) {
431                         throw e;
432                 } catch (Exception e) {
433                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
434                         execution.setVariable("errorCode", "1002")
435                         execution.setVariable("errorText", e.getMessage())
436                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
437                 }
438         }
439         
440         
441
442         /**
443         * Prepare DoUpdateVnfAndModules call.
444         *
445         *
446         * @param execution The flow's execution instance.
447         */
448    public void prepDoUpdateVnfAndModules(DelegateExecution execution) {
449            def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' +
450                    'execution=' + execution.getId() +
451                    ')'
452
453            execution.setVariable('errorCode', "0")
454            msoLogger.trace('Entered ' + method)
455            execution.setVariable("workStep", "doUpdateVnfAndModules")
456            execution.setVariable("failedActivity", "MSO Update VNF")
457            msoLogger.trace('Exited ' + method)
458            
459    }
460         
461         
462         /**
463          * Handle Abort disposition from RainyDayHandler
464          *
465          * @param execution The flow's execution instance.       
466          */
467         public void abortProcessing(DelegateExecution execution) {
468                 def method = getClass().getSimpleName() + '.abortProcessing(' +
469                         'execution=' + execution.getId() +
470                         ')'
471
472                 msoLogger.trace('Entered ' + method)
473                 
474                 def errorText = execution.getVariable("errorText")
475                 def errorCode = execution.getVariable("errorCode")
476                 
477                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
478         }
479         
480         
481
482         
483 }