Merge "update install and configure document"
[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 = reqMap.requestDetails?.cloudConfiguration
171                         def lcpCloudRegionId    = cloudConfiguration.lcpCloudRegionId
172                         execution.setVariable('lcpCloudRegionId', lcpCloudRegionId)
173                         def tenantId = cloudConfiguration.tenantId
174                         execution.setVariable('tenantId', tenantId)
175                         
176                         def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: ''
177                         execution.setVariable('globalSubscriberId', globalSubscriberId)
178                         
179                         execution.setVariable('sdncVersion', '1702')
180
181                         execution.setVariable("UpdateVnfInfraSuccessIndicator", false)
182                                                 
183
184                         
185                         def source = reqMap.requestDetails?.requestInfo?.source
186                         execution.setVariable("source", source)
187                         
188                         //For Completion Handler & Fallout Handler
189                         String requestInfo =
190                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
191                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
192                                         <action>UPDATE</action>
193                                         <source>${MsoUtils.xmlEscape(source)}</source>
194                                    </request-info>"""
195                         
196                         execution.setVariable("requestInfo", requestInfo)                       
197                         
198                         msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo"))         
199                         
200                         msoLogger.trace('Exited ' + method)
201
202                 }
203                 catch(groovy.json.JsonException je) {
204                         msoLogger.debug(" Request is not in JSON format.")
205                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
206
207                 }
208                 catch(Exception e) {
209                         String restFaultMessage = e.getMessage()
210                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
211                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
212                 }       
213         }
214
215         /**
216          * Prepare and send the sychronous response for this flow.
217          *
218          * @param execution The flow's execution instance.
219          */
220         public void sendSynchResponse(DelegateExecution execution) {
221                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
222                         'execution=' + execution.getId() +
223                         ')'
224
225                 msoLogger.trace('Entered ' + method)
226
227
228                 try {
229                         def requestInfo = execution.getVariable('requestInfo')
230                         def requestId = execution.getVariable('requestId')
231                         def source = execution.getVariable('source')
232                         def progress = getNodeTextForce(requestInfo, 'progress')
233                         if (progress.isEmpty()) {
234                                 progress = '0'
235                         }
236                         def startTime = getNodeTextForce(requestInfo, 'start-time')
237                         if (startTime.isEmpty()) {
238                                 startTime = System.currentTimeMillis()
239                         }
240
241                         // RESTResponse (for API Handler (APIH) Reply Task)
242                         def vnfId = execution.getVariable("vnfId")
243                         String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim()
244
245                         sendWorkflowResponse(execution, 200, synchResponse)
246
247                         msoLogger.trace('Exited ' + method)
248                 } catch (BpmnError e) {
249                         throw e;
250                 } catch (Exception e) {
251                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
252                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
253                 }
254         }
255         
256         
257
258         /**
259          * Get VnfResource decomposition object for this VNF.
260          *      
261          *
262          * @param execution The flow's execution instance.
263          */
264         public void getVnfResourceDecomposition(DelegateExecution execution) {
265                 def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' +
266                         'execution=' + execution.getId() +
267                         ')'
268
269                 msoLogger.trace('Entered ' + method)
270
271                 try {
272                         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
273                         String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid')
274                         msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid)
275                         List<VnfResource> vnfResources = serviceDecomposition.getVnfResources()
276                         
277                         for (i in 0..vnfResources.size()-1) {
278                                 ModelInfo modelInfo = vnfResources[i].getModelInfo()
279                                 String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid()
280                                 msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition)
281                                 
282                                 if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) {
283                                         VnfResource vnfResourceDecomposition = vnfResources[i]
284                                         execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition)
285                                         def nfRole = vnfResourceDecomposition.getNfRole()                                       
286                                         execution.setVariable('nfRole', nfRole)
287                                         msoLogger.debug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString())                                 
288                                         break
289                                 }
290                                 else {
291                                         //exception!
292                                 }
293                                 
294                         }
295
296                         msoLogger.trace('Exited ' + method)
297                 } catch (BpmnError e) {
298                         throw e;
299                 } catch (Exception e) {
300                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
301                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage())
302                 }
303         }
304         
305         /**
306          * Check if this VNF is already in maintenance in A&AI.
307          *
308          *
309          * @param execution The flow's execution instance.
310          */
311         public void checkIfVnfInMaintInAAI(DelegateExecution execution) {
312                 def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' +
313                         'execution=' + execution.getId() +
314                         ')'
315
316                 execution.setVariable('errorCode', "0")
317                 execution.setVariable("workStep", "checkIfVnfInMaintInAAI")
318                 execution.setVariable("failedActivity", "AAI")
319                 msoLogger.trace('Entered ' + method)
320
321                 try {
322                         def transactionLoggingUuid = UUID.randomUUID().toString()
323                         AAIRestClientImpl client = new AAIRestClientImpl()
324                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
325                         aaiValidator.setClient(client)
326                         def vnfId = execution.getVariable("vnfId")
327                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid)
328                         msoLogger.debug("isInMaint result: " + isInMaint)
329                         execution.setVariable('isVnfInMaintenance', isInMaint)
330                         
331                         if (isInMaint) {
332                                 execution.setVariable("errorCode", "1003")
333                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
334                         }
335
336
337                         msoLogger.trace('Exited ' + method)
338                 } catch (BpmnError e) {
339                         throw e;
340                 } catch (Exception e) {
341                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);          
342                         execution.setVariable("errorCode", "1002")
343                         execution.setVariable("errorText", e.getMessage())
344                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
345                 }
346         }
347         
348         
349         /**
350          * Check if this VNF's pservers are locked in A&AI.
351          *
352          *
353          * @param execution The flow's execution instance.
354          */
355         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
356                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
357                         'execution=' + execution.getId() +
358                         ')'
359
360                 execution.setVariable('errorCode', "0")
361                 msoLogger.trace('Entered ' + method)
362                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
363                 execution.setVariable("failedActivity", "AAI")
364
365                 try {
366                         def transactionLoggingUuid = UUID.randomUUID().toString()
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, transactionLoggingUuid)
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 }