c588d389469bab62e4dded081668f510b761bd6c
[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.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 org.json.JSONArray
29 import org.json.JSONObject
30
31 import java.beans.MetaData.java_lang_Class_PersistenceDelegate
32 import java.io.Serializable;
33 import java.util.List
34 import java.util.UUID;
35 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
36 import org.camunda.bpm.engine.delegate.BpmnError
37 import org.camunda.bpm.engine.impl.cmd.AbstractSetVariableCmd
38 import org.camunda.bpm.engine.delegate.DelegateExecution
39 import org.openecomp.mso.rest.APIResponse
40 import org.openecomp.mso.rest.RESTClient
41 import org.openecomp.mso.rest.RESTConfig
42 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
43 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
44 import org.openecomp.mso.bpmn.core.RollbackData
45 import org.openecomp.mso.bpmn.core.WorkflowException
46 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
47 import org.openecomp.mso.bpmn.core.json.JsonUtils
48 import org.openecomp.mso.bpmn.core.domain.ModelInfo
49 import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition
50 import org.openecomp.mso.bpmn.core.domain.VnfResource
51 import org.openecomp.mso.client.aai.*
52
53 import org.openecomp.mso.client.appc.ApplicationControllerClient;
54 import org.openecomp.mso.client.appc.ApplicationControllerSupport;
55 import org.openecomp.mso.client.aai.entities.AAIResultWrapper
56 import org.openecomp.mso.client.aai.entities.Relationships
57 import org.openecomp.mso.client.aai.entities.uri.AAIResourceUri
58 import org.openecomp.mso.client.aai.entities.uri.AAIUri
59 import org.openecomp.mso.client.aai.entities.uri.AAIUriFactory
60 import org.onap.appc.client.lcm.model.Action;
61 import org.onap.appc.client.lcm.model.ActionIdentifiers;
62 import org.onap.appc.client.lcm.model.LockInput
63 import org.onap.appc.client.lcm.model.UnlockInput
64 import org.onap.appc.client.lcm.model.HealthCheckInput
65 import org.onap.appc.client.lcm.model.StartInput
66 import org.onap.appc.client.lcm.model.StopInput
67 import org.onap.appc.client.lcm.model.Flags
68 import org.onap.appc.client.lcm.model.Status
69
70
71
72 public abstract class VnfCmBase extends AbstractServiceTaskProcessor {
73
74         ExceptionUtil exceptionUtil = new ExceptionUtil()
75         JsonUtils jsonUtils = new JsonUtils()   
76         def prefix = "VnfIPU_"
77
78         /**
79          * Initialize the flow's variables.
80          *
81          * @param execution The flow's execution instance.
82          */
83         
84         /**
85          * Prepare and send the sychronous response for this flow.
86          *
87          * @param execution The flow's execution instance.
88          */
89         public void sendSynchResponse(DelegateExecution execution) {
90                 def method = getClass().getSimpleName() + '.sendSynchResponse(' +
91                         'execution=' + execution.getId() +
92                         ')'
93                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
94                 logDebug('Entered ' + method, isDebugLogEnabled)
95
96
97                 try {
98                         def requestInfo = execution.getVariable('requestInfo')
99                         def requestId = execution.getVariable('requestId')
100                         def source = execution.getVariable('source')
101                         def progress = getNodeTextForce(requestInfo, 'progress')
102                         if (progress.isEmpty()) {
103                                 progress = '0'
104                         }
105                         def startTime = getNodeTextForce(requestInfo, 'start-time')
106                         if (startTime.isEmpty()) {
107                                 startTime = System.currentTimeMillis()
108                         }
109
110                         // RESTResponse (for API Handler (APIH) Reply Task)
111                         def vnfId = execution.getVariable("vnfId")
112                         String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim()
113
114                         sendWorkflowResponse(execution, 200, synchResponse)
115
116                         logDebug('Exited ' + method, isDebugLogEnabled)
117                 } catch (BpmnError e) {
118                         throw e;
119                 } catch (Exception e) {
120                         logError('Caught exception in ' + method, e)
121                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage())
122                 }
123         }
124         
125         
126
127         /**
128          * Get VnfResource decomposition object for this VNF.
129          *      
130          *
131          * @param execution The flow's execution instance.
132          */
133         public void getVnfResourceDecomposition(DelegateExecution execution) {
134                 def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' +
135                         'execution=' + execution.getId() +
136                         ')'
137                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
138                 logDebug('Entered ' + method, isDebugLogEnabled)
139
140                 try {
141                         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
142                         String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid')
143                         logDebug("vnfModelInvariantUuid: " + vnfModelInvariantUuid, isDebugLogEnabled)
144                         List<VnfResource> vnfResources = serviceDecomposition.getServiceVnfs()
145                         
146                         for (i in 0..vnfResources.size()-1) {
147                                 ModelInfo modelInfo = vnfResources[i].getModelInfo()
148                                 String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid()
149                                 logDebug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition, isDebugLogEnabled)
150                                 
151                                 if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) {
152                                         VnfResource vnfResourceDecomposition = vnfResources[i]
153                                         execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition)
154                                         def nfRole = vnfResourceDecomposition.getNfRole()                                       
155                                         execution.setVariable('nfRole', nfRole)
156                                         logDebug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString(), isDebugLogEnabled)                                     
157                                         break
158                                 }
159                                 else {
160                                         //exception!
161                                 }
162                                 
163                         }
164
165                         logDebug('Exited ' + method, isDebugLogEnabled)
166                 } catch (BpmnError e) {
167                         throw e;
168                 } catch (Exception e) {
169                         logError('Caught exception in ' + method, e)
170                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage())
171                 }
172         }
173         
174         /**
175          * Check if this VNF is already in maintenance in A&AI.
176          *
177          *
178          * @param execution The flow's execution instance.
179          */
180         public void checkIfVnfInMaintInAAI(DelegateExecution execution) {
181                 def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' +
182                         'execution=' + execution.getId() +
183                         ')'
184                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
185                 execution.setVariable('errorCode', "0")
186                 execution.setVariable("workStep", "checkIfVnfInMaintInAAI")
187                 execution.setVariable("failedActivity", "AAI")
188                 logDebug('Entered ' + method, isDebugLogEnabled)
189
190                 try {
191                         def transactionLoggingUuid = UUID.randomUUID().toString()
192                         AAIRestClientImpl client = new AAIRestClientImpl()
193                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
194                         aaiValidator.setClient(client)
195                         def vnfId = execution.getVariable("vnfId")
196                         boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid)
197                         logDebug("isInMaint result: " + isInMaint, isDebugLogEnabled)
198                         execution.setVariable('isVnfInMaintenance', isInMaint)
199                         
200                         if (isInMaint) {
201                                 execution.setVariable("errorCode", "1003")
202                                 execution.setVariable("errorText", "VNF is in maintenance in A&AI")
203                         }
204
205
206                         logDebug('Exited ' + method, isDebugLogEnabled)
207                 } catch (BpmnError e) {
208                         throw e;
209                 } catch (Exception e) {
210                         logError('Caught exception in ' + method, e)                    
211                         execution.setVariable("errorCode", "1002")
212                         execution.setVariable("errorText", e.getMessage())
213                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage())
214                 }
215         }
216         
217         /**
218          * Get VNF info from A&AI.
219          *
220          *
221          * @param execution The flow's execution instance.
222          */
223         public void queryAAIForVnf(DelegateExecution execution) {
224                 def method = getClass().getSimpleName() + '.queryAAIForVnf(' +
225                         'execution=' + execution.getId() +
226                         ')'
227                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
228                 logDebug('Entered ' + method, isDebugLogEnabled)
229
230                 try {
231                         def transactionLoggingUuid = UUID.randomUUID().toString()
232                         def vnfId = execution.getVariable("vnfId")
233                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
234                         def cloudRegionId = execution.getVariable("lcpCloudRegionId")
235                         logDebug("cloudRegionId is: " + cloudRegionId, isDebugLogEnabled)
236                         
237                         AAIResourcesClient client = new AAIResourcesClient()
238                         
239                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
240                         // Check if this VNF exists
241                         if (!client.exists(genericVnfUri)) {
242                                 logDebug("VNF with vnfId " + vnfId + " does not exist in A&AI", isDebugLogEnabled)
243                                 exceptionUtil.buildAndThrowWorkflowException(execution, 404, "VNF with vnfId " + vnfId + " does not exist in A&AI")
244                         }
245                         
246                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
247                         
248                         Map<String, Object> result = aaiRW.asMap()
249                         
250                         String vnfName = result.get("vnf-name")
251                         logDebug("vnfName from A&AI is: " + vnfName, isDebugLogEnabled)
252                         execution.setVariable("vnfName", vnfName)
253                         String nfRole = result.get("nf-role")
254                         logDebug("nfRole from A&AI is: " + nfRole, isDebugLogEnabled)
255                         execution.setVariable("nfRole", nfRole)
256                         String vnfHostIpAddress = result.get("ipv4-oam-address")
257                         logDebug("vnfHostIpAddress from A&AI is: " + vnfHostIpAddress, isDebugLogEnabled)
258                         execution.setVariable("vnfHostIpAddress", vnfHostIpAddress)
259                         execution.setVariable("vmIdList", null)
260                         if (aaiRW.getRelationships() != null) {
261                                 Relationships relationships = aaiRW.getRelationships().get()
262                                 if (relationships != null) {
263                                                 
264                                         List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER)
265                                         JSONArray vserverIds = new JSONArray()
266                                 
267                                         for (AAIResourceUri j in vserverUris) {
268                                                 
269                                                 String vserverId = j.getURIKeys().get('vserver-id')
270                                                 vserverIds.put(vserverId)                                       
271                                         }
272                                 
273                                         JSONObject vmidsArray = new JSONObject()
274                                         vmidsArray.put("vmIds", vserverIds.toString())
275                                 
276                                         logDebug("vmidsArray is: " + vmidsArray.toString(), isDebugLogEnabled)                                                          
277                         
278                                         execution.setVariable("vmIdList", vmidsArray.toString())
279                                 }
280                         }
281                                                 
282                         if (cloudRegionId != null) {                    
283                                 AAIUri cloudRegionUri = AAIUriFactory.createResourceUri(AAIObjectType.DEFAULT_CLOUD_REGION, cloudRegionId)                              
284                                 // Check if this client region exists
285                                 if (!client.exists(cloudRegionUri)) {
286                                         logDebug("Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI", isDebugLogEnabled)
287                                         exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI")
288                                 }
289                         
290                                 AAIResultWrapper aaiRWCloud = client.get(cloudRegionUri)
291                         
292                                 Map<String, Object> resultCloud = aaiRWCloud.asMap()                    
293                         
294                                 String aicIdentity = resultCloud.get("identity-url")
295                                 logDebug("aicIdentity from A&AI is: " + aicIdentity, isDebugLogEnabled)
296                                 execution.setVariable("aicIdentity", aicIdentity)
297                         }
298
299                         logDebug('Exited ' + method, isDebugLogEnabled)
300                 } catch (BpmnError e) {
301                         throw e;
302                 } catch (Exception e) {
303                         logError('Caught exception in ' + method, e)
304                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVnf(): ' + e.getMessage())
305                 }
306         }
307
308         
309         
310         /**
311          * Check if this VNF's pservers are locked in A&AI.
312          *
313          *
314          * @param execution The flow's execution instance.
315          */
316         public void checkIfPserversInMaintInAAI(DelegateExecution execution) {
317                 def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' +
318                         'execution=' + execution.getId() +
319                         ')'
320                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
321                 execution.setVariable('errorCode', "0")
322                 logDebug('Entered ' + method, isDebugLogEnabled)
323                 execution.setVariable("workStep", "checkIfPserversInMaintInAAI")
324                 execution.setVariable("failedActivity", "AAI")
325
326                 try {
327                         def transactionLoggingUuid = UUID.randomUUID().toString()
328                         AAIRestClientImpl client = new AAIRestClientImpl()
329                         AAIValidatorImpl aaiValidator = new AAIValidatorImpl()
330                         aaiValidator.setClient(client)
331                         def vnfId = execution.getVariable("vnfId")                      
332                         boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid)
333                         logDebug("areLocked result: " + areLocked, isDebugLogEnabled)
334                         execution.setVariable('arePserversLocked', areLocked)
335                         
336                         if (areLocked) {
337                                 execution.setVariable("errorCode", "1003")
338                                 execution.setVariable("errorText", "pServers are locked in A&AI")
339                         }                       
340
341                         logDebug('Exited ' + method, isDebugLogEnabled)
342                 } catch (BpmnError e) {
343                         throw e;
344                 } catch (Exception e) {
345                         logError('Caught exception in ' + method, e)
346                         execution.setVariable("errorCode", "1002")
347                         execution.setVariable("errorText", e.getMessage())
348                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage())
349                 }
350         }
351         
352         /**
353          * Set inMaint flag for this VNF to the specified value in A&AI.
354          *
355          *
356          * @param execution The flow's execution instance.
357          * @param inMaint The boolean value of the flag to set
358          */
359         public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) {
360                 def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' +
361                         'execution=' + execution.getId() +
362                         ')'
363                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
364                 execution.setVariable('errorCode', "0")
365                 logDebug('Entered ' + method, isDebugLogEnabled)
366                 if (inMaint) {
367                         execution.setVariable("workStep", "setVnfInMaintFlagInAAI")
368                 }
369                 else {
370                         execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI")
371                 }
372                 execution.setVariable("failedActivity", "AAI")
373
374                 try {
375                         def transactionLoggingUuid = UUID.randomUUID().toString()
376                         AAIRestClientImpl client = new AAIRestClientImpl()
377                         AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl()
378                         aaiUpdator.setClient(client)
379                         def vnfId = execution.getVariable("vnfId")
380                         if (inMaint) {
381                                 aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid)
382                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", true)
383                         }
384                         else {
385                                 aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid)
386                                 execution.setVariable("rollbackSetVnfInMaintenanceFlag", false)
387                         }
388                                                         
389                         logDebug('Exited ' + method, isDebugLogEnabled)
390                 } catch (BpmnError e) {
391                         throw e;
392                 } catch (Exception e) {
393                         logError('Caught exception in ' + method, e)
394                         execution.setVariable("errorCode", "1002")
395                         execution.setVariable("errorText", e.getMessage())
396                         //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage())
397                 }
398         }
399         
400         /**
401          * Check if VF Closed Loop Disabled in A&AI.
402          *
403          *
404          * @param execution The flow's execution instance.
405          */
406         public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) {
407                 def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' +
408                         'execution=' + execution.getId() +
409                         ')'
410                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
411                 execution.setVariable('errorCode', "0")
412                 execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI")
413                 execution.setVariable("failedActivity", "AAI")
414                 logDebug('Entered ' + method, isDebugLogEnabled)
415
416                 try {
417                         def transactionLoggingUuid = UUID.randomUUID().toString()                       
418                         def vnfId = execution.getVariable("vnfId")
419                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
420                         AAIResourcesClient client = new AAIResourcesClient()                    
421                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
422                         AAIResultWrapper aaiRW = client.get(genericVnfUri)
423                         Map<String, Object> result = aaiRW.asMap()
424                         boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false)
425                 
426                         logDebug("isClosedLoopDisabled result: " + isClosedLoopDisabled, isDebugLogEnabled)
427                         execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled)
428                         
429                         if (isClosedLoopDisabled) {
430                                 execution.setVariable("errorCode", "1004")
431                                 execution.setVariable("errorText", "closedLoop is disabled in A&AI")
432                         }
433
434                         logDebug('Exited ' + method, isDebugLogEnabled)
435                 } catch (BpmnError e) {
436                         throw e;
437                 } catch (Exception e) {
438                         logError('Caught exception in ' + method, e)
439                         execution.setVariable("errorCode", "1002")
440                         execution.setVariable("errorText", e.getMessage())              
441                 }
442         }
443         
444         /**
445          * Set VF Closed Loop Disabled Flag in A&AI.
446          *
447          *
448          * @param execution The flow's execution instance.
449          */
450         public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) {
451                 def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' +
452                         'execution=' + execution.getId() +
453                         ')'
454                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
455                 execution.setVariable('errorCode', "0")
456                 if (setDisabled) {
457                         execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI")
458                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", true)
459                 }
460                 else {
461                         execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI")
462                         execution.setVariable("rollbackSetClosedLoopDisabledFlag", false)
463                 }
464                 
465                 execution.setVariable("failedActivity", "AAI")
466                 logDebug('Entered ' + method, isDebugLogEnabled)
467
468                 try {
469                         def transactionLoggingUuid = UUID.randomUUID().toString()
470                         def vnfId = execution.getVariable("vnfId")
471                         AAIResourcesClient client = new AAIResourcesClient()                    
472                         AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
473                         
474                         Map<String, Boolean> request = new HashMap<>()
475                         request.put("is-closed-loop-disabled", setDisabled)
476                         client.update(genericVnfUri, request)
477                         logDebug("set isClosedLoop to: " + setDisabled, isDebugLogEnabled)              
478
479                         logDebug('Exited ' + method, isDebugLogEnabled)
480                 } catch (BpmnError e) {
481                         throw e;
482                 } catch (Exception e) {
483                         logError('Caught exception in ' + method, e)
484                         execution.setVariable("errorCode", "1002")
485                         execution.setVariable("errorText", e.getMessage())                      
486                 }
487         }
488         
489         
490         
491         
492         /**
493          * Call APP-C client to execute specified APP-C command for this VNF.
494          *
495          *
496          * @param execution The flow's execution instance.
497          * @param action The action to take in APP-C.
498          */
499         public void runAppcCommand(DelegateExecution execution, Action action) {
500                 def method = getClass().getSimpleName() + '.runAppcCommand(' +
501                         'execution=' + execution.getId() +
502                         ')'
503                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
504                 execution.setVariable('errorCode', "0")
505                 logDebug('Entered ' + method, isDebugLogEnabled)
506                 
507                 ApplicationControllerClient appcClient = null
508                 
509                 try {
510                         logDebug("Running APP-C action: " + action.toString(), isDebugLogEnabled)
511                         String vnfId = execution.getVariable('vnfId')
512                         String msoRequestId = execution.getVariable('requestId')
513                         execution.setVariable('msoRequestId', msoRequestId)                     
514                         execution.setVariable("failedActivity", "APP-C")
515                         
516                         appcClient = new ApplicationControllerClient()                          
517                         ApplicationControllerSupport support = new ApplicationControllerSupport()                       
518                         appcClient.appCSupport=support                  
519                         org.springframework.test.util.ReflectionTestUtils.setField(support, "lcmModelPackage", "org.onap.appc.client.lcm.model");                       
520                         Flags flags = new Flags();                      
521                         ActionIdentifiers actionIdentifiers = new ActionIdentifiers();                  
522                         actionIdentifiers.setVnfId(vnfId);
523                         Status appcStatus
524                         switch(action) {
525                                 case Action.Lock:
526                                         execution.setVariable('workStep', "LockVNF")
527                                         appcStatus = appcClient.runCommand(Action.Lock,actionIdentifiers,null,msoRequestId)                                     
528                                         break
529                                 case Action.Unlock:
530                                         execution.setVariable('workStep', "UnlockVNF")
531                                         appcStatus = appcClient.runCommand(Action.Unlock,actionIdentifiers,null,msoRequestId)                                   
532                                         break
533                                 case Action.HealthCheck:
534                                         def healthCheckIndex = execution.getVariable('healthCheckIndex')
535                                         execution.setVariable('workStep', "HealthCheckVNF" + healthCheckIndex)
536                                         execution.setVariable('healthCheckIndex', healthCheckIndex + 1)
537                                         appcStatus = appcClient.runCommand(Action.HealthCheck,actionIdentifiers,null,msoRequestId)                                      
538                                         break
539                                 case Action.Start:
540                                         execution.setVariable('workStep', "StartVNF")
541                                         appcStatus = appcClient.runCommand(Action.Start,actionIdentifiers,null,msoRequestId)                                    
542                                         break
543                                 case Action.Stop:
544                                         execution.setVariable('workStep', "StopVNF")
545                                         appcStatus = appcClient.runCommand(Action.Stop,actionIdentifiers,null,msoRequestId)                                     
546                                         break
547                                 default:
548                                         break
549                         }
550                         logDebug("Completed AppC request", isDebugLogEnabled)                   
551                         int appcCode = appcStatus.getCode()
552                         logDebug("AppC status code is: " + appcCode, isDebugLogEnabled)
553                         logDebug("AppC status message is: " + appcStatus.getMessage(), isDebugLogEnabled)
554                         if (support.getCategoryOf(appcStatus) == ApplicationControllerSupport.StatusCategory.ERROR) {
555                                 execution.setVariable("errorCode", Integer.toString(appcCode))
556                                 execution.setVariable("errorText", appcStatus.getMessage())                             
557                         }
558                                 
559                         logDebug('Exited ' + method, isDebugLogEnabled)
560                 } catch (BpmnError e) {
561                         logError('Caught exception in ' + method, e)
562                         execution.setVariable("errorCode", "1002")
563                         execution.setVariable("errorText", e.getMessage())
564                         
565                 } catch (java.lang.NoSuchMethodError e) {
566                         logError('Caught exception in ' + method, e)
567                         execution.setVariable("errorCode", "1002")
568                         execution.setVariable("errorText", e.getMessage())              
569                         
570                 } catch (Exception e) {
571                         logError('Caught exception in ' + method, e)
572                         execution.setVariable("errorCode", "1002")
573                         execution.setVariable("errorText", e.getMessage())      
574                         
575                 }
576         }
577         
578         /**
579          * Placeholder for a call to APP-C client to execute specified APP-C command for this VNF.
580          *
581          *
582          * @param execution The flow's execution instance.
583          * @param action The action to take in APP-C.
584          */
585         public void runAppcCommandPlaceholder(DelegateExecution execution, String action) {
586                 def method = getClass().getSimpleName() + '.runAppcCommandPlaceholder(' +
587                         'execution=' + execution.getId() +
588                         ')'
589                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')              
590                 execution.setVariable('errorCode', "0")
591                 logDebug('Entered ' + method, isDebugLogEnabled)                
592                 execution.setVariable("failedActivity", "APP-C")
593                 execution.setVariable("workStep", action)               
594         }
595
596
597
598
599
600         
601
602         /**
603          * Builds a "CompletionHandler" request and stores it in the specified execution variable.
604          *
605          * @param execution the execution
606          * @param resultVar the execution variable in which the result will be stored
607          */
608         public void completionHandlerPrep(DelegateExecution execution, String resultVar) {
609                 def method = getClass().getSimpleName() + '.completionHandlerPrep(' +
610                         'execution=' + execution.getId() +
611                         ', resultVar=' + resultVar +
612                         ')'
613                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
614                 logDebug('Entered ' + method, isDebugLogEnabled)                
615
616                 try {
617                         
618                         def requestInfo = execution.getVariable('requestInfo')
619
620                         String content = """
621                                 <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
622                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1">
623                                         ${requestInfo}
624                                         <sdncadapterworkflow:status-message>Vnf has been updated successfully.</sdncadapterworkflow:status-message>
625                                         <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name>
626                                 </sdncadapterworkflow:MsoCompletionRequest>
627                         """
628
629                         content = utils.formatXml(content)
630                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
631                         execution.setVariable(resultVar, content)
632
633                         logDebug('Exited ' + method, isDebugLogEnabled)
634                 } catch (BpmnError e) {
635                         throw e;
636                 } catch (Exception e) {
637                         logError('Caught exception in ' + method, e)
638                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error')
639                 }
640         }
641         
642         /**
643         * Prepare DoUpdateVnfAndModules call.
644         *
645         *
646         * @param execution The flow's execution instance.
647         */
648    public void prepDoUpdateVnfAndModules(DelegateExecution execution) {
649            def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' +
650                    'execution=' + execution.getId() +
651                    ')'
652            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
653            execution.setVariable('errorCode', "0")
654            logDebug('Entered ' + method, isDebugLogEnabled)
655            execution.setVariable("workStep", "doUpdateVnfAndModules")
656            execution.setVariable("failedActivity", "MSO Update VNF")
657            logDebug('Exited ' + method, isDebugLogEnabled)
658            
659    }
660         
661         /**
662          * Builds a "FalloutHandler" request and stores it in the specified execution variable.
663          *
664          * @param execution the execution
665          * @param resultVar the execution variable in which the result will be stored
666          */
667         public void falloutHandlerPrep(DelegateExecution execution, String resultVar) {
668                 def method = getClass().getSimpleName() + '.falloutHandlerPrep(' +
669                         'execution=' + execution.getId() +
670                         ', resultVar=' + resultVar +
671                         ')'
672                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
673                 logDebug('Entered ' + method, isDebugLogEnabled)
674
675                 try {
676                         def prefix = execution.getVariable('prefix')                    
677                         def requestInformation = execution.getVariable("requestInfo")           
678                         
679                         def WorkflowException workflowException = execution.getVariable("WorkflowException")
680                         def errorResponseCode = workflowException.getErrorCode()
681                         def errorResponseMsg = workflowException.getErrorMessage()
682                         def encErrorResponseMsg = ""
683                         if (errorResponseMsg != null) {
684                                 encErrorResponseMsg = errorResponseMsg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
685                         }
686
687                         String content = """
688                                 <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
689                                                 xmlns:reqtype="http://org.openecomp/mso/request/types/v1"
690                                                 xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1"
691                                                 xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1">
692                                         ${requestInformation}
693                                         <sdncadapterworkflow:WorkflowException>
694                                                 <sdncadapterworkflow:ErrorMessage>${encErrorResponseMsg}</sdncadapterworkflow:ErrorMessage>
695                                                 <sdncadapterworkflow:ErrorCode>${errorResponseCode}</sdncadapterworkflow:ErrorCode>
696                                         </sdncadapterworkflow:WorkflowException>
697                                 </sdncadapterworkflow:FalloutHandlerRequest>
698                         """
699                         content = utils.formatXml(content)
700                         logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled)
701                         execution.setVariable(resultVar, content)
702
703                         logDebug('Exited ' + method, isDebugLogEnabled)
704                 } catch (BpmnError e) {
705                         throw e;
706                 } catch (Exception e) {
707                         logError('Caught exception in ' + method, e)
708                         exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error')
709                 }
710         }
711         
712         /**
713          * Handle Abort disposition from RainyDayHandler
714          *
715          * @param execution The flow's execution instance.       
716          */
717         public void abortProcessing(DelegateExecution execution) {
718                 def method = getClass().getSimpleName() + '.abortProcessing(' +
719                         'execution=' + execution.getId() +
720                         ')'
721                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
722                 logDebug('Entered ' + method, isDebugLogEnabled)
723                 
724                 def errorText = execution.getVariable("errorText")
725                 def errorCode = execution.getVariable("errorCode")
726                 
727                 exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText)
728         }       
729         
730         /**
731          * Increment Retry Count for Current Work Step
732          *
733          * @param execution The flow's execution instance.
734          */
735         public void incrementRetryCount(DelegateExecution execution) {
736                 def method = getClass().getSimpleName() + '.incrementRetryCount(' +
737                         'execution=' + execution.getId() +
738                         ')'
739                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
740                 logDebug('Entered ' + method, isDebugLogEnabled)
741                 
742                 String retryCountVariableName = execution.getVariable("workStep") + "RetryCount"
743                 execution.setVariable("retryCountVariableName", retryCountVariableName)
744                 
745                 def retryCountVariable = execution.getVariable(retryCountVariableName)
746                 int retryCount = 0
747                 
748                 if (retryCountVariable != null) {
749                         retryCount = (int) retryCountVariable
750                 }
751                 
752                 retryCount += 1
753                 
754                 execution.setVariable(retryCountVariableName, retryCount)
755                 
756                 logDebug("value of " + retryCountVariableName + " is " + retryCount, isDebugLogEnabled)
757                 logDebug('Exited ' + method, isDebugLogEnabled)
758                         
759                 
760         }
761         
762         public void preProcessRollback (DelegateExecution execution) {
763                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
764                 utils.log("DEBUG"," ***** preProcessRollback ***** ", isDebugEnabled)
765                 try {
766                         
767                         Object workflowException = execution.getVariable("WorkflowException");
768  
769                         if (workflowException instanceof WorkflowException) {
770                                 utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled)
771                                 execution.setVariable("prevWorkflowException", workflowException);
772                                 //execution.setVariable("WorkflowException", null);
773                         }
774                 } catch (BpmnError e) {
775                         utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled)
776                 } catch(Exception ex) {
777                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
778                         utils.log("DEBUG", msg, isDebugEnabled)
779                 }
780                 utils.log("DEBUG"," *** Exit preProcessRollback *** ", isDebugEnabled)
781         }
782  
783         public void postProcessRollback (DelegateExecution execution) {
784                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
785                 utils.log("DEBUG"," ***** postProcessRollback ***** ", isDebugEnabled)
786                 String msg = ""
787                 try {
788                         Object workflowException = execution.getVariable("prevWorkflowException");
789                         if (workflowException instanceof WorkflowException) {
790                                 utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled)
791                                 execution.setVariable("WorkflowException", workflowException);
792                         }
793                         
794                 } catch (BpmnError b) {
795                         utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled)
796                         throw b;
797                 } catch(Exception ex) {
798                         msg = "Exception in postProcessRollback. " + ex.getMessage()
799                         utils.log("DEBUG", msg, isDebugEnabled)
800                 }
801                 utils.log("DEBUG"," *** Exit postProcessRollback *** ", isDebugEnabled)
802         }
803  
804
805         
806 }