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