8c1df9b2e7fd56ee03ffb0d0e4687ddd960112f8
[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                         AAIRestClientImpl client = new AAIRestClientImpl()
325                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
326                         aaiValidator.setClient(client)
327                         def vnfId = execution.getVariable("vnfId")
328                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId)
329                         msoLogger.debug("isInMaint result: " + isInMaint)
330                         execution.setVariable('isVnfInMaintenance', isInMaint)
331                         
332                         if (isInMaint) {
333                                 execution.setVariable("errorCode", "1003")
334                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
335                         }
336
337
338                         msoLogger.trace('Exited ' + method)
339                 } catch (BpmnError e) {
340                         throw e;
341                 } catch (Exception e) {
342                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);          
343                         execution.setVariable("errorCode", "1002")
344                         execution.setVariable("errorText", e.getMessage())
345                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
346                 }
347         }
348         
349         
350         /**
351          * Check if this VNF's pservers are locked in A&AI.
352          *
353          *
354          * @param execution The flow's execution instance.
355          */
356         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
357                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
358                         'execution=' + execution.getId() +
359                         ')'
360
361                 execution.setVariable('errorCode', "0")
362                 msoLogger.trace('Entered ' + method)
363                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
364                 execution.setVariable("failedActivity", "AAI")
365
366                 try {
367                         AAIRestClientImpl client = new AAIRestClientImpl()
368                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
369                         aaiValidator.setClient(client)
370                         def vnfId = execution.getVariable("vnfId")                      
371                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId)
372                         msoLogger.debug("areLocked result: " + areLocked)
373                         execution.setVariable('arePserversLocked', areLocked)
374                         
375                         if (areLocked) {
376                                 execution.setVariable("errorCode", "1003")
377                                 execution.setVariable("errorText", "pServers are locked in A&AI")
378                         }
379
380                         msoLogger.trace('Exited ' + method)
381                 } catch (BpmnError e) {
382                         throw e;
383                 } catch (Exception e) {
384                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
385                         execution.setVariable("errorCode", "1002")
386                         execution.setVariable("errorText", e.getMessage())
387                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
388                 }
389         }
390         
391         /**
392          * Set inMaint flag for this VNF to the specified value in A&AI.
393          *
394          *
395          * @param execution The flow's execution instance.
396          * @param inMaint The boolean value of the flag to set
397          */
398         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
399                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
400                         'execution=' + execution.getId() +
401                         ')'
402
403                 execution.setVariable('errorCode', "0")
404                 msoLogger.trace('Entered ' + method)
405                 if (inMaint) {
406                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
407                 }
408                 else {
409                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
410                 }
411                 execution.setVariable("failedActivity", "AAI")
412
413                 try {
414                         def transactionLoggingUuid = UUID.randomUUID().toString()
415                         AAIRestClientImpl client = new AAIRestClientImpl()
416                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
417                         aaiUpdator.setClient(client)
418                         def vnfId = execution.getVariable("vnfId")
419                         if (inMaint) {
420                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
421                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
422                         }
423                         else {
424                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
425                         }
426                                                         
427                         msoLogger.trace('Exited ' + method)
428                 } catch (BpmnError e) {
429                         throw e;
430                 } catch (Exception e) {
431                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
432                         execution.setVariable("errorCode", "1002")
433                         execution.setVariable("errorText", e.getMessage())
434                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
435                 }
436         }
437         
438         
439
440         /**
441         * Prepare DoUpdateVnfAndModules call.
442         *
443         *
444         * @param execution The flow's execution instance.
445         */
446    public void prepDoUpdateVnfAndModules(DelegateExecution execution) {
447            def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' +
448                    'execution=' + execution.getId() +
449                    ')'
450
451            execution.setVariable('errorCode', "0")
452            msoLogger.trace('Entered ' + method)
453            execution.setVariable("workStep", "doUpdateVnfAndModules")
454            execution.setVariable("failedActivity", "MSO Update VNF")
455            msoLogger.trace('Exited ' + method)
456            
457    }
458         
459         
460         /**
461          * Handle Abort disposition from RainyDayHandler
462          *
463          * @param execution The flow's execution instance.       
464          */
465         public void abortProcessing(DelegateExecution execution) {
466                 def method = getClass().getSimpleName() + '.abortProcessing(' +
467                         'execution=' + execution.getId() +
468                         ')'
469
470                 msoLogger.trace('Entered ' + method)
471                 
472                 def errorText = execution.getVariable("errorText")
473                 def errorCode = execution.getVariable("errorCode")
474                 
475                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
476         }
477         
478         
479
480         
481 }