6075f0df9695f2ee925efb8bed14c407db4ddcc8
[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  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.so.bpmn.infrastructure.scripts
23
24 import groovy.json.JsonOutput
25 import groovy.json.JsonSlurper
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.appc.client.lcm.model.Action
29 import org.onap.so.bpmn.common.scripts.ExceptionUtil
30 import org.onap.so.bpmn.common.scripts.MsoUtils
31 import org.onap.so.bpmn.core.json.JsonUtils
32 import org.onap.so.client.aai.*
33 import org.onap.so.client.aai.entities.AAIResultWrapper
34 import org.onap.so.client.aai.entities.uri.AAIUri
35 import org.onap.so.client.aai.entities.uri.AAIUriFactory
36 import org.onap.so.logger.MessageEnum
37 import org.onap.so.logger.MsoLogger
38 import org.slf4j.Logger
39 import org.slf4j.LoggerFactory
40
41 public class VnfConfigUpdate extends VnfCmBase {
42     private static final Logger logger = LoggerFactory.getLogger( VnfConfigUpdate.class)
43
44         ExceptionUtil exceptionUtil = new ExceptionUtil()
45         JsonUtils jsonUtils = new JsonUtils()
46         def prefix = "VnfIPU_"
47
48         /**
49          * Initialize the flow's variables.
50          *
51          * @param execution The flow's execution instance.
52          */
53         public void initProcessVariables(DelegateExecution execution) {
54                 execution.setVariable('prefix', 'VnfCU_')
55                 execution.setVariable('Request', null)
56                 execution.setVariable('source', 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', 'VnfCU')
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('maxRetryCount', 3)
69                 execution.setVariable('retryCount', 0)
70                 execution.setVariable("lcpCloudRegionId", null)
71                 execution.setVariable("rollbackSetClosedLoopDisabledFlag", false)
72                 execution.setVariable("rollbackVnfStop", false)
73                 execution.setVariable("rollbackVnfLock", false)
74                 execution.setVariable("rollbackQuiesceTraffic", false)
75                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", false)
76         }
77
78         /**
79          * Check for missing elements in the received request.
80          *
81          * @param execution The flow's execution instance.
82          */
83         public void preProcessRequest(DelegateExecution execution) {
84                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
85                 'execution=' + execution.getId() +
86                 ')'
87                 initProcessVariables(execution)
88
89         logger.trace('Entered {}', method)
90
91                 initProcessVariables(execution)
92
93                 def incomingRequest = execution.getVariable('bpmnRequest')
94
95         logger.debug("Incoming Infra Request: {}", incomingRequest)
96                 try {
97                         def jsonSlurper = new JsonSlurper()
98                         def jsonOutput = new JsonOutput()
99                         Map reqMap = jsonSlurper.parseText(incomingRequest)
100             logger.debug(" Request is in JSON format.")
101
102                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
103                         def vnfId = execution.getVariable('vnfId')
104
105                         execution.setVariable('serviceInstanceId', serviceInstanceId)
106                         execution.setVariable('vnfId', vnfId)
107                         execution.setVariable('serviceType', 'Mobility')
108                         execution.setVariable('payload', "")
109                         execution.setVariable('actionHealthCheck', Action.HealthCheck)
110                         execution.setVariable('actionConfigModify', Action.ConfigModify)
111
112
113                         def controllerType = reqMap.requestDetails?.requestParameters?.controllerType
114                         execution.setVariable('controllerType', controllerType)
115
116             logger.debug('Controller Type: {}', controllerType)
117
118                         def payload = reqMap.requestDetails?.requestParameters?.payload
119                         execution.setVariable('payload', payload)
120
121             logger.debug('Processed payload: {}', payload)
122
123                         def requestId = execution.getVariable("mso-request-id")
124                         execution.setVariable('requestId', requestId)
125                         execution.setVariable('msoRequestId', requestId)
126
127                         def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null
128                         execution.setVariable('requestorId', requestorId)
129
130                         execution.setVariable('sdncVersion', '1702')
131
132                         execution.setVariable("UpdateVnfInfraSuccessIndicator", false)
133
134
135
136                         def source = reqMap.requestDetails?.requestInfo?.source
137                         execution.setVariable("source", source)
138
139                         //For Completion Handler & Fallout Handler
140                         String requestInfo =
141                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
142                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
143                                         <action>UPDATE</action>
144                                         <source>${MsoUtils.xmlEscape(source)}</source>
145                                    </request-info>"""
146
147                         execution.setVariable("requestInfo", requestInfo)
148
149             logger.debug('RequestInfo: {}', execution.getVariable("requestInfo"))
150
151             logger.trace('Exited {}', method)
152
153                 }
154                 catch(groovy.json.JsonException je) {
155             logger.debug(" Request is not in JSON format.")
156                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format")
157
158                 }
159                 catch(Exception e) {
160                         String restFaultMessage = e.getMessage()
161             logger.error("{} {} {} Exception Encountered - \n {} \n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
162                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), restFaultMessage, e)
163                         exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage)
164                 }
165         }
166
167         /**
168          * Prepare and send the sychronous response for this flow.
169          *
170          * @param execution The flow's execution instance.
171          */
172         public void sendSynchResponse(DelegateExecution execution) {
173                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
174                         'execution=' + execution.getId() +
175                         ')'
176
177         logger.trace('Entered {}', method)
178
179
180                 try {
181                         def requestInfo = execution.getVariable('requestInfo')
182                         def requestId = execution.getVariable('requestId')
183                         def source = execution.getVariable('source')
184                         def progress = getNodeTextForce(requestInfo, 'progress')
185                         if (progress.isEmpty()) {
186                                 progress = '0'
187                         }
188                         def startTime = getNodeTextForce(requestInfo, 'start-time')
189                         if (startTime.isEmpty()) {
190                                 startTime = System.currentTimeMillis()
191                         }
192
193                         // RESTResponse (for API Handler (APIH) Reply Task)
194                         def vnfId = execution.getVariable("vnfId")
195                         String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim()
196
197                         sendWorkflowResponse(execution, 200, synchResponse)
198
199             logger.trace('Exited {}', method)
200                 } catch (BpmnError e) {
201                         throw e;
202                 } catch (Exception e) {
203             logger.error("{} {} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
204                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
205                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
206                 }
207         }
208
209
210         /**
211          * Check if this VNF is already in maintenance in A&AI.
212          *
213          *
214          * @param execution The flow's execution instance.
215          */
216         public void checkIfVnfInMaintInAAI(DelegateExecution execution) {
217                 def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' +
218                         'execution=' + execution.getId() +
219                         ')'
220
221                 execution.setVariable('errorCode', "0")
222                 execution.setVariable("workStep", "checkIfVnfInMaintInAAI")
223                 execution.setVariable("failedActivity", "AAI")
224         logger.trace('Entered {}', method)
225
226                 try {
227                         AAIRestClientImpl client = new AAIRestClientImpl()
228                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
229                         aaiValidator.setClient(client)
230                         def vnfId = execution.getVariable("vnfId")
231                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId)
232             logger.debug("isInMaint result: {}", isInMaint)
233                         execution.setVariable('isVnfInMaintenance', isInMaint)
234
235                         if (isInMaint) {
236                                 execution.setVariable("errorCode", "1003")
237                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
238                         }
239
240             logger.trace('Exited {}', method)
241                 } catch (BpmnError e) {
242                         throw e;
243                 } catch (Exception e) {
244             logger.error("{} {} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
245                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
246                         execution.setVariable("errorCode", "1002")
247                         execution.setVariable("errorText", e.getMessage())
248                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
249                 }
250         }
251
252
253         /**
254          * Check if this VNF's pservers are locked in A&AI.
255          *
256          *
257          * @param execution The flow's execution instance.
258          */
259         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
260                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
261                         'execution=' + execution.getId() +
262                         ')'
263
264                 execution.setVariable('errorCode', "0")
265         logger.trace('Entered {}', method)
266                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
267                 execution.setVariable("failedActivity", "AAI")
268
269                 try {
270                         AAIRestClientImpl client = new AAIRestClientImpl()
271                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
272                         aaiValidator.setClient(client)
273                         def vnfId = execution.getVariable("vnfId")
274                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId)
275             logger.debug("areLocked result: {}", areLocked)
276                         execution.setVariable('arePserversLocked', areLocked)
277
278                         if (areLocked) {
279                                 execution.setVariable("errorCode", "1003")
280                                 execution.setVariable("errorText", "pServers are locked in A&AI")
281                         }
282
283             logger.trace('Exited {}', method)
284                 } catch (BpmnError e) {
285                         throw e;
286                 } catch (Exception e) {
287             logger.error("{} {} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
288                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
289                         execution.setVariable("errorCode", "1002")
290                         execution.setVariable("errorText", e.getMessage())
291                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
292                 }
293         }
294
295         /**
296          * Set inMaint flag for this VNF to the specified value in A&AI.
297          *
298          *
299          * @param execution The flow's execution instance.
300          * @param inMaint The boolean value of the flag to set
301          */
302         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
303                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
304                         'execution=' + execution.getId() +
305                         ')'
306
307                 execution.setVariable('errorCode', "0")
308         logger.trace('Entered {}', method)
309                 if (inMaint) {
310                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
311                         execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
312                 }
313                 else {
314                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
315                 }
316                 execution.setVariable("failedActivity", "AAI")
317
318                 try {
319                         AAIRestClientImpl client = new AAIRestClientImpl()
320                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
321                         aaiUpdator.setClient(client)
322                         def vnfId = execution.getVariable("vnfId")
323                         if (inMaint) {
324                                 aaiUpdator.updateVnfToLocked(vnfId)
325                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
326                         }
327                         else {
328                                 aaiUpdator.updateVnfToUnLocked(vnfId)
329                         }
330
331             logger.trace('Exited {}', method)
332                 } catch (BpmnError e) {
333                         throw e;
334                 } catch (Exception e) {
335             logger.error("{} {} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
336                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
337                         execution.setVariable("errorCode", "1002")
338                         execution.setVariable("errorText", e.getMessage())
339                 }
340         }
341
342         /**
343          * Check if VF Closed Loop Disabled in A&AI.
344          *
345          *
346          * @param execution The flow's execution instance.
347          */
348         public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) {
349                 def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' +
350                         'execution=' + execution.getId() +
351                         ')'
352
353                 execution.setVariable('errorCode', "0")
354                 execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI")
355                 execution.setVariable("failedActivity", "AAI")
356         logger.trace('Entered {}', method)
357
358                 try {
359                         def transactionLoggingUuid = UUID.randomUUID().toString()
360                         def vnfId = execution.getVariable("vnfId")
361             logger.debug("vnfId is: {}", vnfId)
362                         AAIResourcesClient client = new AAIResourcesClient()
363                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
364                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
365                         Map<String, Object> result = aaiRW.asMap()
366                         boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false)
367
368             logger.debug("isClosedLoopDisabled result: {}", isClosedLoopDisabled)
369                         execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled)
370
371                         if (isClosedLoopDisabled) {
372                                 execution.setVariable("errorCode", "1004")
373                                 execution.setVariable("errorText", "closedLoop is disabled in A&AI")
374                         }
375
376             logger.trace('Exited {}', method)
377                 } catch (BpmnError e) {
378                         throw e;
379                 } catch (Exception e) {
380             logger.error("{} {} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
381                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
382                         execution.setVariable("errorCode", "1002")
383                         execution.setVariable("errorText", e.getMessage())
384                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
385                 }
386         }
387
388         /**
389          * Set VF Closed Loop Disabled Flag in A&AI.
390          *
391          *
392          * @param execution The flow's execution instance.
393          */
394         public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) {
395                 def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' +
396                         'execution=' + execution.getId() +
397                         ')'
398
399                 execution.setVariable('errorCode', "0")
400                 if (setDisabled) {
401                         execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI")
402                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", true)
403                 }
404                 else {
405                         execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI")
406                 }
407
408                 execution.setVariable("failedActivity", "AAI")
409         logger.trace('Entered {}', method)
410
411                 try {
412                         def transactionLoggingUuid = UUID.randomUUID().toString()
413                         def vnfId = execution.getVariable("vnfId")
414                         AAIResourcesClient client = new AAIResourcesClient()
415                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
416
417                         Map<String, Boolean> request = new HashMap<>()
418                         request.put("is-closed-loop-disabled", setDisabled)
419                         client.update(genericVnfUri, request)
420             logger.debug("set isClosedLoop to: {}", setDisabled)
421
422             logger.trace('Exited {}', method)
423                 } catch (BpmnError e) {
424                         throw e;
425                 } catch (Exception e) {
426             logger.error("{} {} {} Caught exception in {}\n ", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
427                     MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), method, e)
428                         execution.setVariable("errorCode", "1002")
429                         execution.setVariable("errorText", e.getMessage())
430                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
431                 }
432         }
433
434
435         /**
436          * Handle Abort disposition from RainyDayHandler
437          *
438          * @param execution The flow's execution instance.
439          */
440         public void abortProcessing(DelegateExecution execution) {
441                 def method = getClass().getSimpleName() + '.abortProcessing(' +
442                         'execution=' + execution.getId() +
443                         ')'
444
445         logger.trace('Entered {}', method)
446
447                 def errorText = execution.getVariable("errorText")
448                 def errorCode = execution.getVariable("errorCode")
449
450                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
451         }
452
453         /**
454          * Increment Retry Count for Current Work Step
455          *
456          * @param execution The flow's execution instance.
457          */
458         public void incrementRetryCount(DelegateExecution execution) {
459                 def method = getClass().getSimpleName() + '.incrementRetryCount(' +
460                         'execution=' + execution.getId() +
461                         ')'
462
463         logger.trace('Entered {}', method)
464
465                 String retryCountVariableName = execution.getVariable("workStep") + "RetryCount"
466                 execution.setVariable("retryCountVariableName", retryCountVariableName)
467
468                 def retryCountVariable = execution.getVariable(retryCountVariableName)
469                 int retryCount = 0
470
471                 if (retryCountVariable != null) {
472                         retryCount = (int) retryCountVariable
473                 }
474
475                 retryCount += 1
476
477                 execution.setVariable(retryCountVariableName, retryCount)
478
479         logger.debug("value of {} is {}", retryCountVariableName, retryCount)
480         logger.trace('Exited {}', method)
481     }
482
483 }