8ca28719168b928babfb62d189b65c401905da46
[so.git] /
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                         def transactionLoggingUuid = UUID.randomUUID().toString()
223                         AAIRestClientImpl client = new AAIRestClientImpl()
224                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
225                         aaiValidator.setClient(client)
226                         def vnfId = execution.getVariable("vnfId")
227                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid)
228                         msoLogger.debug("isInMaint result: " + isInMaint)
229                         execution.setVariable('isVnfInMaintenance', isInMaint)
230                         
231                         if (isInMaint) {
232                                 execution.setVariable("errorCode", "1003")
233                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
234                         }
235
236                         msoLogger.trace('Exited ' + method)
237                 } catch (BpmnError e) {
238                         throw e;
239                 } catch (Exception e) {
240                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);                  
241                         execution.setVariable("errorCode", "1002")
242                         execution.setVariable("errorText", e.getMessage())
243                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
244                 }
245         }
246         
247         
248         /**
249          * Check if this VNF's pservers are locked in A&AI.
250          *
251          *
252          * @param execution The flow's execution instance.
253          */
254         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
255                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
256                         'execution=' + execution.getId() +
257                         ')'
258
259                 execution.setVariable('errorCode', "0")
260                 msoLogger.trace('Entered ' + method)
261                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
262                 execution.setVariable("failedActivity", "AAI")
263
264                 try {
265                         def transactionLoggingUuid = UUID.randomUUID().toString()
266                         AAIRestClientImpl client = new AAIRestClientImpl()
267                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
268                         aaiValidator.setClient(client)
269                         def vnfId = execution.getVariable("vnfId")                      
270                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid)
271                         msoLogger.debug("areLocked result: " + areLocked)
272                         execution.setVariable('arePserversLocked', areLocked)
273                         
274                         if (areLocked) {
275                                 execution.setVariable("errorCode", "1003")
276                                 execution.setVariable("errorText", "pServers are locked in A&AI")
277                         }
278
279
280                         msoLogger.trace('Exited ' + method)
281                 } catch (BpmnError e) {
282                         throw e;
283                 } catch (Exception e) {
284                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
285                         execution.setVariable("errorCode", "1002")
286                         execution.setVariable("errorText", e.getMessage())
287                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
288                 }
289         }
290         
291         /**
292          * Set inMaint flag for this VNF to the specified value in A&AI.
293          *
294          *
295          * @param execution The flow's execution instance.
296          * @param inMaint The boolean value of the flag to set
297          */
298         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
299                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
300                         'execution=' + execution.getId() +
301                         ')'
302
303                 execution.setVariable('errorCode', "0")
304                 msoLogger.trace('Entered ' + method)
305                 if (inMaint) {
306                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
307                         execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
308                 }
309                 else {
310                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
311                 }
312                 execution.setVariable("failedActivity", "AAI")
313
314                 try {
315                         def transactionLoggingUuid = UUID.randomUUID().toString()
316                         AAIRestClientImpl client = new AAIRestClientImpl()
317                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
318                         aaiUpdator.setClient(client)
319                         def vnfId = execution.getVariable("vnfId")
320                         if (inMaint) {
321                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
322                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
323                         }
324                         else {
325                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
326                         }
327                                                         
328                         msoLogger.trace('Exited ' + method)
329                 } catch (BpmnError e) {
330                         throw e;
331                 } catch (Exception e) {
332                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
333                         execution.setVariable("errorCode", "1002")
334                         execution.setVariable("errorText", e.getMessage())
335                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
336                 }
337         }
338         
339         /**
340          * Check if VF Closed Loop Disabled in A&AI.
341          *
342          *
343          * @param execution The flow's execution instance.
344          */
345         public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) {
346                 def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' +
347                         'execution=' + execution.getId() +
348                         ')'
349
350                 execution.setVariable('errorCode', "0")
351                 execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI")
352                 execution.setVariable("failedActivity", "AAI")
353                 msoLogger.trace('Entered ' + method)
354
355                 try {
356                         def transactionLoggingUuid = UUID.randomUUID().toString()
357                         def vnfId = execution.getVariable("vnfId")
358                         msoLogger.debug("vnfId is: " + vnfId)
359                         AAIResourcesClient client = new AAIResourcesClient()                    
360                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
361                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
362                         Map<String, Object> result = aaiRW.asMap()
363                         boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false)
364                 
365                         msoLogger.debug("isClosedLoopDisabled result: " + isClosedLoopDisabled)
366                         execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled)
367                         
368                         if (isClosedLoopDisabled) {
369                                 execution.setVariable("errorCode", "1004")
370                                 execution.setVariable("errorText", "closedLoop is disabled in A&AI")
371                         }
372
373                         msoLogger.trace('Exited ' + method)
374                 } catch (BpmnError e) {
375                         throw e;
376                 } catch (Exception e) {
377                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
378                         execution.setVariable("errorCode", "1002")
379                         execution.setVariable("errorText", e.getMessage())
380                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
381                 }
382         }
383         
384         /**
385          * Set VF Closed Loop Disabled Flag in A&AI.
386          *
387          *
388          * @param execution The flow's execution instance.
389          */
390         public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) {
391                 def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' +
392                         'execution=' + execution.getId() +
393                         ')'
394
395                 execution.setVariable('errorCode', "0")
396                 if (setDisabled) {
397                         execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI")
398                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", true)
399                 }
400                 else {
401                         execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI")
402                 }
403                 
404                 execution.setVariable("failedActivity", "AAI")
405                 msoLogger.trace('Entered ' + method)
406
407                 try {
408                         def transactionLoggingUuid = UUID.randomUUID().toString()
409                         def vnfId = execution.getVariable("vnfId")
410                         AAIResourcesClient client = new AAIResourcesClient()                    
411                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
412                         
413                         Map<String, Boolean> request = new HashMap<>()
414                         request.put("is-closed-loop-disabled", setDisabled)
415                         client.update(genericVnfUri, request)
416                         msoLogger.debug("set isClosedLoop to: " + setDisabled)          
417
418
419                         msoLogger.trace('Exited ' + method)
420                 } catch (BpmnError e) {
421                         throw e;
422                 } catch (Exception e) {
423                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
424                         execution.setVariable("errorCode", "1002")
425                         execution.setVariable("errorText", e.getMessage())
426                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
427                 }
428         }       
429
430         
431         /**
432          * Handle Abort disposition from RainyDayHandler
433          *
434          * @param execution The flow's execution instance.       
435          */
436         public void abortProcessing(DelegateExecution execution) {
437                 def method = getClass().getSimpleName() + '.abortProcessing(' +
438                         'execution=' + execution.getId() +
439                         ')'
440
441                 msoLogger.trace('Entered ' + method)
442                 
443                 def errorText = execution.getVariable("errorText")
444                 def errorCode = execution.getVariable("errorCode")
445                 
446                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
447         }
448         
449         /**
450          * Increment Retry Count for Current Work Step
451          *
452          * @param execution The flow's execution instance.
453          */
454         public void incrementRetryCount(DelegateExecution execution) {
455                 def method = getClass().getSimpleName() + '.incrementRetryCount(' +
456                         'execution=' + execution.getId() +
457                         ')'
458
459                 msoLogger.trace('Entered ' + method)
460                 
461                 String retryCountVariableName = execution.getVariable("workStep") + "RetryCount"
462                 execution.setVariable("retryCountVariableName", retryCountVariableName)
463                 
464                 def retryCountVariable = execution.getVariable(retryCountVariableName)
465                 int retryCount = 0
466                 
467                 if (retryCountVariable != null) {
468                         retryCount = (int) retryCountVariable
469                 }               
470                 
471                 retryCount += 1
472                 
473                 execution.setVariable(retryCountVariableName, retryCount)
474                 
475                 msoLogger.debug("value of " + retryCountVariableName + " is " + retryCount)
476                 msoLogger.trace('Exited ' + method)
477                         
478                 
479         }
480         
481         
482         
483 }