Merge "asdc process vf resource into db bug fix"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / VnfConfigUpdate.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.json.JsonUtils
28 import org.onap.so.client.aai.*
29 import org.onap.so.client.aai.entities.AAIResultWrapper
30 import org.onap.so.client.aai.entities.uri.AAIUri
31 import org.onap.so.client.aai.entities.uri.AAIUriFactory
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 VnfConfigUpdate extends VnfCmBase {
39         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VnfConfigUpdate.class);
40
41         ExceptionUtil exceptionUtil = new ExceptionUtil()
42         JsonUtils jsonUtils = new JsonUtils()   
43         def prefix = "VnfIPU_"
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', 'VnfCU_')
52                 execution.setVariable('Request', null)                  
53                 execution.setVariable('source', null)                   
54                 execution.setVariable('controllerType', null)                   
55                 execution.setVariable('UpdateVnfSuccessIndicator', false)
56                 execution.setVariable('serviceType', null)
57                 execution.setVariable('nfRole', null)
58                 execution.setVariable('currentActivity', 'VnfCU')
59                 execution.setVariable('workStep', null)
60                 execution.setVariable('failedActivity', null)
61                 execution.setVariable('errorCode', "0")
62                 execution.setVariable('errorText', null)
63                 execution.setVariable('healthCheckIndex0', 0)
64                 execution.setVariable('healthCheckIndex1', 1)
65                 execution.setVariable('maxRetryCount', 3)
66                 execution.setVariable('retryCount', 0)
67                 execution.setVariable("lcpCloudRegionId", null)
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                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
100                         def vnfId = execution.getVariable('vnfId')
101                         
102                         execution.setVariable('serviceInstanceId', serviceInstanceId)
103                         execution.setVariable('vnfId', vnfId)                   
104                         execution.setVariable('serviceType', 'Mobility')
105                         execution.setVariable('payload', "")
106                         execution.setVariable('actionHealthCheck', Action.HealthCheck)
107                         execution.setVariable('actionConfigModify', Action.ConfigModify)                        
108                         
109
110                         def controllerType = reqMap.requestDetails?.requestParameters?.controllerType
111                         execution.setVariable('controllerType', controllerType)
112                         
113                         msoLogger.debug('Controller Type: ' + controllerType)                   
114                         
115                         def payload = reqMap.requestDetails?.requestParameters?.payload
116                         execution.setVariable('payload', payload)
117                         
118                         msoLogger.debug('Processed payload: ' + payload)
119                         
120                         def requestId = execution.getVariable("mso-request-id")
121                         execution.setVariable('requestId', requestId)
122                         execution.setVariable('msoRequestId', requestId)                        
123                         
124                         def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null
125                         execution.setVariable('requestorId', requestorId)
126                         
127                         execution.setVariable('sdncVersion', '1702')
128
129                         execution.setVariable("UpdateVnfInfraSuccessIndicator", false)
130                                                 
131
132                         
133                         def source = reqMap.requestDetails?.requestInfo?.source
134                         execution.setVariable("source", source)
135                         
136                         //For Completion Handler & Fallout Handler
137                         String requestInfo =
138                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
139                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
140                                         <action>UPDATE</action>
141                                         <source>${MsoUtils.xmlEscape(source)}</source>
142                                    </request-info>"""
143                         
144                         execution.setVariable("requestInfo", requestInfo)                       
145                         
146                         msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo"))         
147                         
148                         msoLogger.trace('Exited ' + method)
149
150                 }
151                 catch(groovy.json.JsonException je) {
152                         msoLogger.debug(" Request is not in JSON format.")
153                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
154
155                 }
156                 catch(Exception e) {
157                         String restFaultMessage = e.getMessage()
158                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
159                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
160                 }       
161         }
162
163         /**
164          * Prepare and send the sychronous response for this flow.
165          *
166          * @param execution The flow's execution instance.
167          */
168         public void sendSynchResponse(DelegateExecution execution) {
169                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
170                         'execution=' + execution.getId() +
171                         ')'
172
173                 msoLogger.trace('Entered ' + method)
174
175
176                 try {
177                         def requestInfo = execution.getVariable('requestInfo')
178                         def requestId = execution.getVariable('requestId')
179                         def source = execution.getVariable('source')
180                         def progress = getNodeTextForce(requestInfo, 'progress')
181                         if (progress.isEmpty()) {
182                                 progress = '0'
183                         }
184                         def startTime = getNodeTextForce(requestInfo, 'start-time')
185                         if (startTime.isEmpty()) {
186                                 startTime = System.currentTimeMillis()
187                         }
188
189                         // RESTResponse (for API Handler (APIH) Reply Task)
190                         def vnfId = execution.getVariable("vnfId")
191                         String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim()
192
193                         sendWorkflowResponse(execution, 200, synchResponse)
194
195                         msoLogger.trace('Exited ' + method)
196                 } catch (BpmnError e) {
197                         throw e;
198                 } catch (Exception e) {
199                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
200                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
201                 }
202         }       
203         
204         
205         /**
206          * Check if this VNF is already in maintenance in A&AI.
207          *
208          *
209          * @param execution The flow's execution instance.
210          */
211         public void checkIfVnfInMaintInAAI(DelegateExecution execution) {
212                 def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' +
213                         'execution=' + execution.getId() +
214                         ')'
215
216                 execution.setVariable('errorCode', "0")
217                 execution.setVariable("workStep", "checkIfVnfInMaintInAAI")
218                 execution.setVariable("failedActivity", "AAI")
219                 msoLogger.trace('Entered ' + method)
220
221                 try {
222                         AAIRestClientImpl client = new AAIRestClientImpl()
223                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
224                         aaiValidator.setClient(client)
225                         def vnfId = execution.getVariable("vnfId")
226                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId)
227                         msoLogger.debug("isInMaint result: " + isInMaint)
228                         execution.setVariable('isVnfInMaintenance', isInMaint)
229                         
230                         if (isInMaint) {
231                                 execution.setVariable("errorCode", "1003")
232                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
233                         }
234
235                         msoLogger.trace('Exited ' + method)
236                 } catch (BpmnError e) {
237                         throw e;
238                 } catch (Exception e) {
239                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);                  
240                         execution.setVariable("errorCode", "1002")
241                         execution.setVariable("errorText", e.getMessage())
242                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
243                 }
244         }
245         
246         
247         /**
248          * Check if this VNF's pservers are locked in A&AI.
249          *
250          *
251          * @param execution The flow's execution instance.
252          */
253         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
254                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
255                         'execution=' + execution.getId() +
256                         ')'
257
258                 execution.setVariable('errorCode', "0")
259                 msoLogger.trace('Entered ' + method)
260                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
261                 execution.setVariable("failedActivity", "AAI")
262
263                 try {
264                         AAIRestClientImpl client = new AAIRestClientImpl()
265                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
266                         aaiValidator.setClient(client)
267                         def vnfId = execution.getVariable("vnfId")                      
268                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId)
269                         msoLogger.debug("areLocked result: " + areLocked)
270                         execution.setVariable('arePserversLocked', areLocked)
271                         
272                         if (areLocked) {
273                                 execution.setVariable("errorCode", "1003")
274                                 execution.setVariable("errorText", "pServers are locked in A&AI")
275                         }
276
277
278                         msoLogger.trace('Exited ' + method)
279                 } catch (BpmnError e) {
280                         throw e;
281                 } catch (Exception e) {
282                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
283                         execution.setVariable("errorCode", "1002")
284                         execution.setVariable("errorText", e.getMessage())
285                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
286                 }
287         }
288         
289         /**
290          * Set inMaint flag for this VNF to the specified value in A&AI.
291          *
292          *
293          * @param execution The flow's execution instance.
294          * @param inMaint The boolean value of the flag to set
295          */
296         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
297                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
298                         'execution=' + execution.getId() +
299                         ')'
300
301                 execution.setVariable('errorCode', "0")
302                 msoLogger.trace('Entered ' + method)
303                 if (inMaint) {
304                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
305                         execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
306                 }
307                 else {
308                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
309                 }
310                 execution.setVariable("failedActivity", "AAI")
311
312                 try {
313                         def transactionLoggingUuid = UUID.randomUUID().toString()
314                         AAIRestClientImpl client = new AAIRestClientImpl()
315                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
316                         aaiUpdator.setClient(client)
317                         def vnfId = execution.getVariable("vnfId")
318                         if (inMaint) {
319                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
320                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
321                         }
322                         else {
323                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
324                         }
325                                                         
326                         msoLogger.trace('Exited ' + method)
327                 } catch (BpmnError e) {
328                         throw e;
329                 } catch (Exception e) {
330                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
331                         execution.setVariable("errorCode", "1002")
332                         execution.setVariable("errorText", e.getMessage())
333                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
334                 }
335         }
336         
337         /**
338          * Check if VF Closed Loop Disabled in A&AI.
339          *
340          *
341          * @param execution The flow's execution instance.
342          */
343         public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) {
344                 def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' +
345                         'execution=' + execution.getId() +
346                         ')'
347
348                 execution.setVariable('errorCode', "0")
349                 execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI")
350                 execution.setVariable("failedActivity", "AAI")
351                 msoLogger.trace('Entered ' + method)
352
353                 try {
354                         def transactionLoggingUuid = UUID.randomUUID().toString()
355                         def vnfId = execution.getVariable("vnfId")
356                         msoLogger.debug("vnfId is: " + vnfId)
357                         AAIResourcesClient client = new AAIResourcesClient()                    
358                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
359                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
360                         Map<String, Object> result = aaiRW.asMap()
361                         boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false)
362                 
363                         msoLogger.debug("isClosedLoopDisabled result: " + isClosedLoopDisabled)
364                         execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled)
365                         
366                         if (isClosedLoopDisabled) {
367                                 execution.setVariable("errorCode", "1004")
368                                 execution.setVariable("errorText", "closedLoop is disabled in A&AI")
369                         }
370
371                         msoLogger.trace('Exited ' + method)
372                 } catch (BpmnError e) {
373                         throw e;
374                 } catch (Exception e) {
375                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
376                         execution.setVariable("errorCode", "1002")
377                         execution.setVariable("errorText", e.getMessage())
378                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
379                 }
380         }
381         
382         /**
383          * Set VF Closed Loop Disabled Flag in A&AI.
384          *
385          *
386          * @param execution The flow's execution instance.
387          */
388         public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) {
389                 def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' +
390                         'execution=' + execution.getId() +
391                         ')'
392
393                 execution.setVariable('errorCode', "0")
394                 if (setDisabled) {
395                         execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI")
396                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", true)
397                 }
398                 else {
399                         execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI")
400                 }
401                 
402                 execution.setVariable("failedActivity", "AAI")
403                 msoLogger.trace('Entered ' + method)
404
405                 try {
406                         def transactionLoggingUuid = UUID.randomUUID().toString()
407                         def vnfId = execution.getVariable("vnfId")
408                         AAIResourcesClient client = new AAIResourcesClient()                    
409                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
410                         
411                         Map<String, Boolean> request = new HashMap<>()
412                         request.put("is-closed-loop-disabled", setDisabled)
413                         client.update(genericVnfUri, request)
414                         msoLogger.debug("set isClosedLoop to: " + setDisabled)          
415
416
417                         msoLogger.trace('Exited ' + method)
418                 } catch (BpmnError e) {
419                         throw e;
420                 } catch (Exception e) {
421                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
422                         execution.setVariable("errorCode", "1002")
423                         execution.setVariable("errorText", e.getMessage())
424                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
425                 }
426         }       
427
428         
429         /**
430          * Handle Abort disposition from RainyDayHandler
431          *
432          * @param execution The flow's execution instance.       
433          */
434         public void abortProcessing(DelegateExecution execution) {
435                 def method = getClass().getSimpleName() + '.abortProcessing(' +
436                         'execution=' + execution.getId() +
437                         ')'
438
439                 msoLogger.trace('Entered ' + method)
440                 
441                 def errorText = execution.getVariable("errorText")
442                 def errorCode = execution.getVariable("errorCode")
443                 
444                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
445         }
446         
447         /**
448          * Increment Retry Count for Current Work Step
449          *
450          * @param execution The flow's execution instance.
451          */
452         public void incrementRetryCount(DelegateExecution execution) {
453                 def method = getClass().getSimpleName() + '.incrementRetryCount(' +
454                         'execution=' + execution.getId() +
455                         ')'
456
457                 msoLogger.trace('Entered ' + method)
458                 
459                 String retryCountVariableName = execution.getVariable("workStep") + "RetryCount"
460                 execution.setVariable("retryCountVariableName", retryCountVariableName)
461                 
462                 def retryCountVariable = execution.getVariable(retryCountVariableName)
463                 int retryCount = 0
464                 
465                 if (retryCountVariable != null) {
466                         retryCount = (int) retryCountVariable
467                 }               
468                 
469                 retryCount += 1
470                 
471                 execution.setVariable(retryCountVariableName, retryCount)
472                 
473                 msoLogger.debug("value of " + retryCountVariableName + " is " + retryCount)
474                 msoLogger.trace('Exited ' + method)
475                         
476                 
477         }
478         
479         
480         
481 }